博客
关于我
利用zxing生成二维码
阅读量:141 次
发布时间:2019-02-26

本文共 5152 字,大约阅读时间需要 17 分钟。

Java QR Code工具类详解

工具类概述

本文介绍一个功能强大的Java QR Code工具类QRCodeUtil,该工具类可用于快速生成带有图片嵌入的二维码,并支持解码操作。本文将详细介绍工具类的功能实现原理、使用方法以及示例代码。

工具类功能概述

核心功能

  • 二维码生成

    • 支持指定二维码内容和图片嵌入。
    • 提供尺寸设置和错误校正级别配置。
    • 自动生成二维码图片文件。
    • 支持图片压缩优化。
  • 二维码解码

    • 支持读取二维码内容。
    • 提供错误校正功能,确保解码准确性。
  • 图片处理

    • 自动生成带有二维码的图片。
    • 支持图片缩放优化,确保图片质量与尺寸合理。
  • 文件管理

    • 创建所需的文件目录。
    • 支持二维码图片的存储路径自定义。
  • 工具类实现细节

    依赖项配置

    在项目中添加依赖项:

    com.google.zxing
    core
    3.3.0

    主要类结构

    package com.example.qrcode;public class QRCodeUtil {    // 字符集设置    private static final String CHARSET = "utf-8";    // 二维码尺寸    private static final int QRCODE_SIZE = 300;    // LOGO尺寸    private static final int WIDTH = 60;    private static final int HEIGHT = 60;    // 二维码生成相关    public static BufferedImage createImage(String content, String imgPath, boolean needCompress) throws Exception {        // 设置编码字符集        Map
    hints = new HashMap<>(); hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); hints.put(EncodeHintType.CHARACTER_SET, CHARSET); hints.put(EncodeHintType.MARGIN, 1); // 生成二维码矩阵 BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints); // 创建图片 BufferedImage image = new BufferedImage(bitMatrix.getWidth(), bitMatrix.getHeight(), BufferedImage.TYPE_INT_RGB); for (int x = 0; x < bitMatrix.getWidth(); x++) { for (int y = 0; y < bitMatrix.getHeight(); y++) { image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF); } } // 处理图片嵌入或压缩 if (imgPath == null || "".equals(imgPath)) { return image; } // 插入图片 insertImage(image, imgPath, needCompress); return image; } // 插入图片逻辑 private static void insertImage(BufferedImage source, String imgPath, boolean needCompress) throws Exception { File file = new File(imgPath); if (!file.exists()) { System.err.println("图片文件不存在:" + imgPath); return; } // 读取图片 Image src = ImageIO.read(file); // 处理图片缩放 if (needCompress) { int width = src.getWidth(null); int height = src.getHeight(null); if (width > WIDTH || height > HEIGHT) { // 缩放图片 Image scaledImage = src.getScaledInstance(WIDTH, HEIGHT, Image.SCALE_SMOOTH); BufferedImage tag = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); Graphics g = tag.getGraphics(); g.drawImage(scaledImage, 0, 0, null); g.dispose(); src = scaledImage; } } // 绘制图片到二维码 Graphics2D graph = source.createGraphics(); int x = (QRCODE_SIZE - src.getWidth(null)) / 2; int y = (QRCODE_SIZE - src.getHeight(null)) / 2; graph.drawImage(src, x, y, WIDTH, HEIGHT, null); // 绘制圆角边框 Shape shape = new RoundRectangle2D.Float(x, y, WIDTH, HEIGHT, 6, 6); BasicStroke stroke = new BasicStroke(3f); graph.setStroke(stroke); graph.draw(shape); graph.dispose(); } // 生成二维码图片 public static void encode(String content, String imgPath, String destPath, boolean needCompress) throws Exception { BufferedImage image = createImage(content, imgPath, needCompress); mkdirs(destPath); ImageIO.write(image, "JPG", new File(destPath)); } // 创建目录 private static void mkdirs(String destPath) { File file = new File(destPath); if (!file.exists() && !file.isDirectory()) { file.mkdirs(); } } // 其他方法(省略部分代码)}

    解码实现

    public static String decode(File file) throws Exception {    BufferedImage image = ImageIO.read(file);    if (image == null) {        return null;    }    BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);    BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));    Map
    hints = new Hashtable<>(); hints.put(DecodeHintType.CHARACTER_SET, CHARSET); Result result = new MultiFormatReader().decode(bitmap, hints); return result.getText();}

    使用方法

    生成二维码

    // 示例:生成带有图片的二维码QRCodeUtil.encode("http://example.com", "path/to/image.jpg", "output/jpg", true);

    解码二维码

    // 示例:读取二维码内容String result = QRCodeUtil.decode(new File("path/to/output.jpg"));

    注意事项

  • 图片处理:建议图片路径正确,且图片格式支持JPG或PNG。
  • 压缩优化:图片压缩可提高生成速度,但需平衡图片质量。
  • 二维码尺寸:默认尺寸为300x300像素,可根据需求调整。
  • 错误校正:默认使用H级别错误校正,确保解码可靠性。
  • 开源依赖

    本工具类基于Zing图形库,依赖项配置如下:

    com.google.zxing
    core
    3.3.0

    示例应用

    public class QrCodeTest {    public static void main(String[] args) throws Exception {        // 二维码内容        String text = "https://blog.csdn.net/liuno0";        // 图片路径        String imgPath = "E:/图像/juan_/juan_backup3.jpg";        // 输出路径        String destPath = "D:/liunn/liunn.jpg";        // 生成二维码        QRCodeUtil.encode(text, imgPath, destPath, true);        // 解码二维码        String decodedText = QRCodeUtil.decode(new File(destPath));        System.out.println("解码结果:" + decodedText);    }}

    总结

    通过本文介绍的QRCodeUtil工具类,开发人员可以快速实现二维码的生成与解码功能。工具类支持图片嵌入、尺寸自定义、错误校正等高级功能,适合在多种应用场景中使用。

    你可能感兴趣的文章
    NIS服务器的配置过程
    查看>>
    Nitrux 3.8 发布!性能全面提升,带来非凡体验
    查看>>
    NiuShop开源商城系统 SQL注入漏洞复现
    查看>>
    NI笔试——大数加法
    查看>>
    NLog 自定义字段 写入 oracle
    查看>>
    NLog类库使用探索——详解配置
    查看>>
    NLP 基于kashgari和BERT实现中文命名实体识别(NER)
    查看>>
    NLP 模型中的偏差和公平性检测
    查看>>
    Vue3.0 性能提升主要是通过哪几方面体现的?
    查看>>
    NLP 项目:维基百科文章爬虫和分类【01】 - 语料库阅读器
    查看>>
    NLP_什么是统计语言模型_条件概率的链式法则_n元统计语言模型_马尔科夫链_数据稀疏(出现了词库中没有的词)_统计语言模型的平滑策略---人工智能工作笔记0035
    查看>>
    NLP三大特征抽取器:CNN、RNN与Transformer全面解析
    查看>>
    NLP学习笔记:使用 Python 进行NLTK
    查看>>
    NLP度量指标BELU真的完美么?
    查看>>
    NLP的不同研究领域和最新发展的概述
    查看>>
    NLP的神经网络训练的新模式
    查看>>
    NLP采用Bert进行简单文本情感分类
    查看>>
    NLP问答系统:使用 Deepset SQUAD 和 SQuAD v2 度量评估
    查看>>
    NLP项目:维基百科文章爬虫和分类【02】 - 语料库转换管道
    查看>>
    NLP:使用 SciKit Learn 的文本矢量化方法
    查看>>