java后台生成Base64二维码

  直接上代码

引入依赖

<dependency>
			<groupId>com.google.zxing</groupId>
			<artifactId>javase</artifactId>
			<version>3.2.1</version>
		</dependency>

实现方法 

	// 创建二维码  content为二维码内容 width,height是二维码大小
	public static String crateB64QRCode(String content, int width, int height) {

		String resultImage = "";
		if (!StringUtils.isEmpty(content)) {
			ServletOutputStream stream = null;
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			@SuppressWarnings("rawtypes")
			HashMap<EncodeHintType, Comparable> hints = new HashMap<>();
			hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 指定字符编码为“utf-8”
			hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); // 指定二维码的纠错等级为中级
			hints.put(EncodeHintType.MARGIN, 2); // 设置图片的边距

			try {
				QRCodeWriter writer = new QRCodeWriter();
				BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, width, height, hints);

				BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
				ImageIO.write(bufferedImage, "png", os);
				/**
				 * 原生转码前面没有 data:image/png;base64 这些字段,返回给前端是无法被解析,可以让前端加,也可以在下面加上
				 */
				resultImage = new String("data:image/png;base64," + Base64.encodeBase64String(os.toByteArray()));
				return resultImage;
			} catch (Exception e) {
				logger.info("二维码生成异常:" + e.getMessage());
			} finally {
				if (stream != null) {
					try {
						stream.flush();
						stream.close();
					} catch (IOException e) {
						logger.info("servlet输出流关闭异常:" + e.getMessage());
					}

				}
			}
		}
		return resultImage;
	}

man方法调用

public static void main(String[] args)  {
		String qr=crateB64QRCode("https://www.baidu.com", 200, 200);
	System.out.println(qr);
}

运行结果

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADIAQAAAACFI5MzAAABGElEQVR42u2YQRLCIAxF0xXH4KYFbsoxWIE/CaW16tZkUUYdzHPxpySfP9L4teghD/kzyYQVc6ipxdL4y+aGFLy5FrHB56w4IY02IV2EZ4reCDY9sHyHBGeu2n0ROW1IzuFrH1gSnZKizfhlfizJXKgF0fvhO4akjEoifMJ2cRdrgkIadZNHuwf+VXJDOs8H9FaUsdnD6kQPZFqLGHPdz060J7ATCNfCfYKtyZyMdnTiqMkNWSmAWLvYsxtSpPtkVmDMOO3rXWJPksSToZbc1gTbE138RGV2iydyps4xZr5zQzQF5OOuKOLQXoimzikf0B3JfNPKyx9Zo/zuLtZEUycdkpsjMlOnXLnoxx7uidiQPP8fPMSevAA6vfI0CIVIDwAAAABJRU5ErkJggg==
 

 

放入img标签

如图

 

扫码后转到百度,

这种编码图片不可以加文字和水印,可以下载,但是给图片重命名下载后是损坏的,也许是我的方法有问题,展示还是可以的啦

如果出现下面异常:

java.lang.InternalError: java.lang.reflect.InvocationTargetException
	at java.desktop/sun.font.FontManagerFactory$1.run(FontManagerFactory.java:86)
	at java.base/java.security.AccessController.doPrivileged(AccessController.java:312)
	at 

请尝试在tomcat的bin目录下 catalina.sh

添加

JAVA_OPTS="$JAVA_OPTS -Djava.awt.headless=true"

保存重启 tomcat

 

 

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值