1.引入依赖
引入zxing的依赖
1 2 3 4 5 6 7 8 9 10 11
| <dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.5.1</version> </dependency> <dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>3.5.1</version> </dependency>
|
2.字节流输出图片
在后台生成二维码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| @RequestMapping(value = "img") public void qrcodeimg(@RequestBody(required = false) String jsonStr){ try { response.setCharacterEncoding("UTF-8"); response.reset();
response.setContentType("image/".concat("jpeg").concat(";charset=UTF-8")); response.setHeader("Content-Disposition", "inline; filename=\"qrcode.jpeg\"");
if(jsonStr==null||jsonStr.isEmpty()){ jsonStr="http://www.proheng.net"; }
byte[] fileBytes =qRcodeZxingUtils.generateQRcodeByte(jsonStr,256,"jpeg") ; ServletOutputStream os = response.getOutputStream(); os.write(fileBytes); os.flush(); os.close(); }catch (Exception e){ logger.error("qrcodeimg",e); } }
|
其中生成二维码的代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
public byte[] generateQRcodeByte(String content, int width, String picFormat) { byte[] codeBytes = null; try { BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, width); BufferedImage image = toBufferedImage(bitMatrix);
ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageIO.write(image, picFormat, out);
codeBytes = out.toByteArray();
} catch (WriterException | IOException e) { e.printStackTrace(); } return codeBytes; }
|
参考文章:
1.图片流输出到前台成图片预览显示
2.java生成QR二维码 这个主要参考文章:1.二维码的原理主要是依靠斜左上方的三个矩形框来进行定位,然后解析图片的黑白像素对应计算机编码的01操作。那么如果是二维码里面藏的东西过多的时候,二维码可能会很丑陋,几个定位符非常的小,里面的黑白点非常的密集。这个时候不妨尝试一下利用缓存,二维码里面只藏有简单的随机字符串,然后再根据扫描得到的字符串去请求缓存拿到真正的有用信息。(这种就是代理的思想);2.在第1点的基础上,有时候二维码就是为了做登陆的,要求极高的安全性。在二维码里面藏了一下检验,防串改的字串,比如jwtToken。那么这个二维码很有可能会非常丑,遇到了不懂技术的产品,可能要你改需求。低效的沟通还不如直接拿巨头的成本给他看,直接拿微信公众平台(https://mp.weixin.qq.com/)的登陆页面二维码给他看,让对方明白为了安全有的时候不得不牺牲美观。
3.Java后端生成二维码,Base64后,前端直接使用
4.聊聊 Web 项目二维码生成的最佳姿势 将二维码生成放在了前端,这种流程的实现方式,完全摒弃了后端生成二维码的部分代码、将生成二维码图片放入项目路径的两个过程。前端随用随生成,需要注意的是返回给前端的跳转链接中的参数需要加密处理,毕竟前端是个是非之地。
3.生成base64字符串
可以使用zxing库将内容生成一个base64的字符串,前端引用的时候,只需要使用img标签的src指向这个字符串就可以了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| ByteArrayOutputStream os=new ByteArrayOutputStream(); HashMap<EncodeHintType,Comparable> hints=new HashMap<>(); hints.put(EncodeHintType.CHARACTER_SET,"UTF-8"); hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); hints.put(EncodeHintType.MARGIN,2); QRCodeWriter qrCodeWriter=new QRCodeWriter(); BitMatrix bitMatrix=qrCodeWriter.encode(qrCodeUrl, BarcodeFormat.QR_CODE,200,200,hints);
BufferedImage bufferedImage= MatrixToImageWriter.toBufferedImage(bitMatrix); ImageIO.write(bufferedImage,"png",os);
String resultImage=new String("data:image/png;base64,"+ Base64.encode(os.toByteArray()));
|
参考文章:
1.SpringBoot 使用 zxing 生成二维码 返回Base64编码