• Java 生成二维码 zxing生成二维码 条形码 服务端生成二维码 Java生成条形码


    Java 生成二维码 zxing生成二维码 条形码 服务端生成二维码 Java生成条形码

    一、关于ZXing

            1、ZXing是谷歌开源的支持二维码、条形码 等图形的生成类库;支持生成、和解码功能。 Github主页API文档介绍文档 

    二、依赖 pom.xml

            1、javase.jar

    1. <dependency>
    2. <groupId>com.google.zxinggroupId>
    3. <artifactId>javaseartifactId>
    4. <version>3.3.0version>
    5. dependency>

    三、生成二维码、条形码 和解码

            1、生成二维码

    1. /**
    2. * description: 生成二维码
    3. * @param content 二维码内容
    4. * @param width 宽
    5. * @param height 高
    6. * @param targetPath 生成二维码位置
    7. * @param imgType 图片类型-- jpg/png/gif 等
    8. * @throws Exception
    9. * @return void
    10. * @version v1.0
    11. * @author w
    12. * @date 2020年8月27日 上午10:41:37
    13. */
    14. public static void genQRCode(String content ,String targetPath ,String imgType , int width ,int height)throws Exception{
    15. Map hints = new HashMap<>();
    16. //内容编码格式
    17. hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
    18. // 指定纠错等级
    19. hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
    20. //设置二维码边的空度,非负数
    21. hints.put(EncodeHintType.MARGIN, 1);
    22. BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
    23. MatrixToImageWriter.writeToPath(bitMatrix, imgType, new File(targetPath).toPath());// 输出原图片
    24. }

            2、解析二维码

    1. /**
    2. * description: 解析二维码
    3. * @param imgPath
    4. * @return
    5. * @throws Exception
    6. * @return String
    7. * @version v1.0
    8. * @author w
    9. * @date 2020年8月27日 上午11:22:42
    10. */
    11. @SuppressWarnings("unchecked")
    12. public static String readQRCode(String imgPath) throws Exception {
    13. File file = new File(imgPath);
    14. if(!file.exists() && !file.isFile()) {
    15. throw new RuntimeException("file not found ,"+ imgPath);
    16. }
    17. MultiFormatReader formatReader = new MultiFormatReader();
    18. //读取指定的二维码文件
    19. BufferedImage bufferedImage =ImageIO.read(file);
    20. BinaryBitmap binaryBitmap= new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(bufferedImage)));
    21. //定义二维码参数
    22. Map hints= new HashMap<>();
    23. hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
    24. Result result = formatReader.decode(binaryBitmap , hints);
    25. return result.getText();
    26. }

            3、生成条形码

    1. /**
    2. * description: 生成条形码
    3. * @param contents 条形码内容
    4. * @param width 条形码宽
    5. * @param height 条形码高
    6. * @param imgPath 图片存储路径
    7. * @return void
    8. * @version v1.0
    9. * @author w
    10. * @date 2020年8月27日 上午11:30:12
    11. */
    12. public static void genBarCode(String contents, int width, int height, String imgPath) {
    13. int codeWidth = 3 + // start guard
    14. (7 * 6) + // left bars
    15. 5 + // middle guard
    16. (7 * 6) + // right bars
    17. 3; // end guard
    18. codeWidth = Math.max(codeWidth, width);
    19. try {
    20. BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,
    21. BarcodeFormat.EAN_13, codeWidth, height, null);
    22. MatrixToImageWriter
    23. .writeToFile(bitMatrix, "png", new File(imgPath));
    24. } catch (Exception e) {
    25. e.printStackTrace();
    26. }
    27. }

            4、解析条形码

    1. /**
    2. * description: 解析条形码
    3. * @param imgPath
    4. * @return String
    5. * @version v1.0
    6. * @author w
    7. * @date 2020年8月27日 上午11:30:27
    8. */
    9. public static String decode(String imgPath) {
    10. BufferedImage image = null;
    11. Result result = null;
    12. try {
    13. image = ImageIO.read(new File(imgPath));
    14. if (image == null) {
    15. System.out.println("the decode image may be not exit.");
    16. }
    17. LuminanceSource source = new BufferedImageLuminanceSource(image);
    18. BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
    19. result = new MultiFormatReader().decode(bitmap, null);
    20. return result.getText();
    21. } catch (Exception e) {
    22. e.printStackTrace();
    23. }
    24. return null;
    25. }

    四、web页面返回二维码

            1、二维码转换为 Buffer

    1. /**
    2. * description: 生成二维码的 Buffer 二进制文件
    3. * @param content
    4. * @param imgType
    5. * @param width
    6. * @param height
    7. * @throws Exception
    8. * @return BufferedImage
    9. * @version v1.0
    10. * @author w
    11. * @date 2020年9月7日 下午5:33:03
    12. */
    13. public static BufferedImage genQRCodeToBuffer(String content ,String imgType , int width ,int height)throws Exception{
    14. Map hints = new HashMap<>();
    15. //内容编码格式
    16. hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
    17. // 指定纠错等级
    18. hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
    19. //设置二维码边的空度,非负数
    20. hints.put(EncodeHintType.MARGIN, 1);
    21. BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
    22. BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
    23. return bufferedImage;
    24. }

            2、SpringMVC 设置返回 图片

    1. @RequestMapping(value = {"/gen"})
    2. public void gen(String name ,HttpServletRequest request , HttpServletResponse response) throws Exception {
    3. System.out.println(" name :" + name);
    4. if(null == name || name == "") {
    5. response.setContentType("application/json;charset=UTF-8");
    6. response.setCharacterEncoding("UTF-8");
    7. response.getWriter().print(" name can't be blank ,名字不能为空");
    8. return;
    9. }
    10. response.setHeader("Pragma", "no-cache");
    11. response.setHeader("Cache-Control", "no-cache");
    12. response.setDateHeader("Expires", 0);
    13. response.setContentType("image/jpeg");
    14. BufferedImage genQRCodeToBuffer = ZXingUtils.genQRCodeToBuffer(name);
    15. ImageIO.write(genQRCodeToBuffer , "jpeg" ,response.getOutputStream());
    16. }

    五、总结

            1、本示例是简单记录了使用 zxing生成二维码、条形码编码和解码的过程;若有更高的需求,如:批量生成、解析等,二维码带Logo 等,可根据本示例代码进行修改定制,也可以私信哈 ^_^ !

    前端生成二维码: 使用jquery qrcode生成二维码图片分享到朋友圈打印二维码_HaHa_Sir的博客-CSDN博客

  • 相关阅读:
    当 K8s资源管理 与 JVM参数(Xms、Xmx)相遇
    微信小程序通过 movable-area 做一个与vuedraggable相似的上下拖动排序控件
    自制操作系统日志——第十五天
    传统软件架构与微服务架构
    SQL Server详细使用教程(包含启动SQL server服务、建立数据库、建表的详细操作) 非常适合初学者
    MySQL实现事务隔离的原理
    STM32单片机控制直流电机实现PID闭环控制源码集锦
    面试知识点整理:Skia 架构的场景渲染
    Ubuntu下配置hive
    Docker--harbor
  • 原文地址:https://blog.csdn.net/HaHa_Sir/article/details/126847334