首先,确保你在项目中引入了 zxing 库。可以通过 Maven 引入以下依赖:

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

QRCodeUtils 实现代码:

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.Result;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

/**
 * QRCodeUtils 是一个二维码操作工具类,支持二维码生成、保存、解析等功能。
 */
public class QRCodeUtils {

    // 定义二维码图片的默认宽度和高度
    private static final int WIDTH = 300;
    private static final int HEIGHT = 300;

    // 定义二维码图片的格式
    private static final String IMAGE_FORMAT = "png";

    /**
     * 生成二维码并将其保存到指定路径
     *
     * @param content  二维码的内容
     * @param filePath 二维码保存的文件路径
     * @throws Exception 如果二维码生成失败
     */
    public static void generateQRCode(String content, String filePath) throws Exception {
        generateQRCode(content, filePath, WIDTH, HEIGHT);
    }

    /**
     * 生成二维码并将其保存到指定路径,支持自定义宽高
     *
     * @param content  二维码的内容
     * @param filePath 二维码保存的文件路径
     * @param width    二维码的宽度
     * @param height   二维码的高度
     * @throws Exception 如果二维码生成失败
     */
    public static void generateQRCode(String content, String filePath, int width, int height) throws Exception {
        // 设置二维码参数
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 高级别容错
        hints.put(EncodeHintType.MARGIN, 1); // 边距

        // 生成二维码矩阵
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);

        // 将二维码图片保存到指定路径
        Path path = new File(filePath).toPath();
        MatrixToImageWriter.writeToPath(bitMatrix, IMAGE_FORMAT, path);
    }

    /**
     * 生成二维码并返回 BufferedImage 对象
     *
     * @param content 二维码的内容
     * @return BufferedImage 二维码图片
     * @throws Exception 如果二维码生成失败
     */
    public static BufferedImage generateQRCodeImage(String content) throws Exception {
        return generateQRCodeImage(content, WIDTH, HEIGHT);
    }

    /**
     * 生成二维码并返回 BufferedImage 对象,支持自定义宽高
     *
     * @param content 二维码的内容
     * @param width   二维码的宽度
     * @param height  二维码的高度
     * @return BufferedImage 二维码图片
     * @throws Exception 如果二维码生成失败
     */
    public static BufferedImage generateQRCodeImage(String content, int width, int height) throws Exception {
        // 设置二维码参数
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 高级别容错
        hints.put(EncodeHintType.MARGIN, 1); // 边距

        // 生成二维码矩阵
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);

        // 将二维码矩阵转换为 BufferedImage 对象
        return MatrixToImageWriter.toBufferedImage(bitMatrix);
    }

    /**
     * 解析二维码图片,获取其中的内容
     *
     * @param filePath 二维码图片的文件路径
     * @return 二维码的内容
     * @throws Exception 如果二维码解析失败
     */
    public static String decodeQRCode(String filePath) throws Exception {
        File file = new File(filePath);
        BufferedImage bufferedImage = ImageIO.read(file);
        return decodeQRCode(bufferedImage);
    }

    /**
     * 解析二维码图片,获取其中的内容
     *
     * @param bufferedImage 二维码的 BufferedImage 对象
     * @return 二维码的内容
     * @throws Exception 如果二维码解析失败
     */
    public static String decodeQRCode(BufferedImage bufferedImage) throws Exception {
        // 创建 BinaryBitmap 对象
        BufferedImageLuminanceSource luminanceSource = new BufferedImageLuminanceSource(bufferedImage);
        BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(luminanceSource));

        // 设置解码参数
        Map<DecodeHintType, Object> hints = new HashMap<>();
        hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");

        // 解码二维码
        Result result = new MultiFormatReader().decode(binaryBitmap, hints);
        return result.getText();
    }

    /**
     * 保存二维码图片到指定文件路径
     *
     * @param image    BufferedImage 对象
     * @param filePath 保存文件路径
     * @throws IOException 如果保存失败
     */
    public static void saveQRCodeImage(BufferedImage image, String filePath) throws IOException {
        File file = new File(filePath);
        ImageIO.write(image, IMAGE_FORMAT, file);
    }

    public static void main(String[] args) {
        try {
            // 生成二维码
            String content = "https://example.com";
            String filePath = "example_qr_code.png";
            generateQRCode(content, filePath);
            System.out.println("二维码已生成,文件路径: " + filePath);

            // 解析二维码
            String decodedContent = decodeQRCode(filePath);
            System.out.println("二维码内容: " + decodedContent);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

详细说明:

1. 生成二维码

generateQRCode 方法用于生成二维码,并将其保存到指定路径。二维码的内容通过 content 参数传入,支持自定义宽度和高度。二维码图像的格式默认为 PNG。

  • 使用 MultiFormatWriter 创建 BitMatrix 对象,该对象包含二维码的位置信息。
  • 利用 MatrixToImageWriter.writeToPath() 方法,将 BitMatrix 对象写入指定路径,生成二维码图片。
2. 解析二维码

decodeQRCode 方法用于解析二维码图片,返回其中的文本内容。可以传入文件路径,也可以传入一个 BufferedImage 对象来解析。

  • 使用 MultiFormatReader 类来解析二维码,解码结果存储在 Result 对象中。
  • 通过调用 Result.getText() 方法来获取二维码中的文本信息。
3. 保存二维码图片

saveQRCodeImage 方法用于将生成的 BufferedImage 对象保存到文件系统中。指定保存路径和图片格式(默认为 PNG),使用 ImageIO.write() 方法将 BufferedImage 写入文件。

4. 自定义二维码大小

工具类提供了多种生成二维码的方式,用户可以选择使用默认的宽高(300x300),也可以自定义宽度和高度来生成二维码图片。

5. 容错处理

二维码生成和解析时,设置了高级别容错机制 ErrorCorrectionLevel.H,这使得二维码即使部分受损,仍能保持一定的解码能力。

应用场景:

  • 网站链接分享:生成二维码以便快速分享网站链接或其他内容。
  • 产品信息编码:可以将产品信息生成二维码,以方便客户扫描获取详细信息。
  • 身份验证和支付:二维码可以用于身份验证、支付等场景。

QRCodeUtils 工具类适合用于常见的二维码生成和解析需求,并可根据实际需求进行扩展,比如添加二维码带 Logo、生成彩色二维码等功能。

总结:

生成二维码:

  1. 首先,QRCodeUtils类提供了一个静态方法generateQRCode,接受字符串和文件路径作为参数。
  2. 在这个方法中,使用ZXing库来生成二维码。ZXing是一个流行的开源库,用于生成和解析二维码。
  3. 首先,创建一个BitMatrix对象来保存二维码的位图表示。
  4. 然后,使用MatrixToImageWriter类将BitMatrix对象转换为图片文件并保存到指定的文件路径。

解析二维码:

  1. QRCodeUtils类还提供了一个静态方法decodeQRCode,接受文件路径作为参数。
  2. 在这个方法中,使用ZXing库来解析二维码。
  3. 首先,使用BufferedImage对象读取二维码图片文件。
  4. 然后,使用MultiFormatReader类来解析图像,得到Result对象。
  5. 最后,从Result对象中提取出二维码中包含的信息并返回。

QRCodeUtils是一个方便的Java工具类,用于生成和解析二维码。它使用ZXing库来实现这些功能,并提供了简单易用的静态方法。使用这个工具类,我们可以轻松地生成二维码图片,并从图片中解析出二维码中的信息。

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐