此贴作废。。。经试用,数据传输量太大,已经放弃了

首先说一下需求,一般的二维码都是随便保存在硬盘上某个地方。但是最近弄security,静态资源怎么也访问不到。有谁知道怎么解决吗?急~~在线等。但是二维码又不能不显示。一直想玩一下Base64编码图片,于是就试验了一下。记录下来。
生成二维码:代码一搜大把,我就贴下我的吧,这里面有个地方要注意,我没有吧生成的qrcode保存为文件,而是直接取流使用Base64编码存进了数据库,这样再也不用担心我的二维码找不到了!
Maven: 只需要添加这一个就行了
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.2.1</version>
</dependency>
/**
* 生成二维码并使用Base64编码
* @param content
* @throws Exception
*/
public String getBase64QRCode(String content)
throws Exception {
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
@SuppressWarnings("rawtypes")
Map hints = new HashMap();
//设置二维码四周白色区域的大小
hints.put(EncodeHintType.MARGIN,1);
//设置二维码的容错性
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
//画二维码
BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 400, 400, hints);
BufferedImage image = toBufferedImage(bitMatrix);
//注意此处拿到字节数据
byte[] bytes =imageToBytes(image,"jpg");
//Base64编码
String base64String = Base64.getEncoder().encodeToString(bytes);
return base64String;
}
代码没啥好说的,注意一点Base64.getEncoder().encodeToString
方法从java 1.8以上才支持。
网页中显示的时候要加上前缀:data:image/jpg;base64,
疗效:

网友评论