Java 生成/解析二维码

版权声明:如果觉得我的博客对你有帮助, 请点赞或评论! https://blog.csdn.net/zongf0504/article/details/87941448

google 提供了zxing 工具包用来生成和解析二维码, 可以支持纯文本二维码或图片二维码.

1. zxing测试demo

笔者创建的是基于maven 的javaSE 项目, 直接添加依赖即可. 若没有maven 环境, 直接下载zxing jar包, 然后添加环境变量即可.

1.1 添加ZXing依赖

只需要引入一个zxing 核心包即可, 笔者为了测试方便, 所以引入了一个单元测试包junit

<!-- 引入二维码依赖 -->
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.2.1</version>
</dependency>

<!-- 引入单元测试依赖 -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>

1.2 自定义LuminanceSource

当二维码中嵌入图片时, 需要创建自定义LuminanceSource.

package org.zongf.learn.qrcoder;

import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;

import com.google.zxing.LuminanceSource;

public class BufferedImageLuminanceSource extends LuminanceSource {

    private final BufferedImage image;
    private final int left;
    private final int top;

    public BufferedImageLuminanceSource(BufferedImage image) {
        this(image, 0, 0, image.getWidth(), image.getHeight());
    }

    public BufferedImageLuminanceSource(BufferedImage image, int left, int top, int width, int height) {
        super(width, height);

        int sourceWidth = image.getWidth();
        int sourceHeight = image.getHeight();
        if (left + width > sourceWidth || top + height > sourceHeight) {
            throw new IllegalArgumentException("Crop rectangle does not fit within image data.");
        }

        for (int y = top; y < top + height; y++) {
            for (int x = left; x < left + width; x++) {
                if ((image.getRGB(x, y) & 0xFF000000) == 0) {
                    image.setRGB(x, y, 0xFFFFFFFF); // = white
                }
            }
        }

        this.image = new BufferedImage(sourceWidth, sourceHeight, BufferedImage.TYPE_BYTE_GRAY);
        this.image.getGraphics().drawImage(image, 0, 0, null);
        this.left = left;
        this.top = top;
    }

    public byte[] getRow(int y, byte[] row) {
        if (y < 0 || y >= getHeight()) {
            throw new IllegalArgumentException("Requested row is outside the image: " + y);
        }
        int width = getWidth();
        if (row == null || row.length < width) {
            row = new byte[width];
        }
        image.getRaster().getDataElements(left, top + y, width, 1, row);
        return row;
    }

    public byte[] getMatrix() {
        int width = getWidth();
        int height = getHeight();
        int area = width * height;
        byte[] matrix = new byte[area];
        image.getRaster().getDataElements(left, top, width, height, matrix);
        return matrix;
    }

    public boolean isCropSupported() {
        return true;
    }

    public LuminanceSource crop(int left, int top, int width, int height) {
        return new BufferedImageLuminanceSource(image, this.left + left, this.top + top, width, height);
    }

    public boolean isRotateSupported() {
        return true;
    }

    public LuminanceSource rotateCounterClockwise() {
        int sourceWidth = image.getWidth();
        int sourceHeight = image.getHeight();
        AffineTransform transform = new AffineTransform(0.0, -1.0, 1.0, 0.0, 0.0, sourceWidth);
        BufferedImage rotatedImage = new BufferedImage(sourceHeight, sourceWidth, BufferedImage.TYPE_BYTE_GRAY);
        Graphics2D g = rotatedImage.createGraphics();
        g.drawImage(image, transform, null);
        g.dispose();
        int width = getWidth();
        return new BufferedImageLuminanceSource(rotatedImage, top, sourceWidth - (left + width), getHeight(), width);
    }
}

1.3 创建二维码读写工具类

package org.zongf.learn.qrcoder;

import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Shape;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;

import javax.imageio.ImageIO;

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.Result;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

/**
 * 二维码工具类
 */
public class QRCodeUtil {

    /** 字符编码UTF-8 */
    private static final String CHARSET_UTF8 = "utf-8";

    /***
     * 生成二维码图片
     * @param content 二维码携带文本内容
     * @return BufferedImage
     * @throws Exception
     */
    private static BufferedImage createImage(String content,int qrSize) throws Exception {
        HashMap<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET_UTF8);
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, qrSize, qrSize, hints);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        return image;
    }

    /**
     * 图片中嵌入图片(二维码中插入logo)
     * @param qrBi 二维码BufferedImage
     * @param imgPath
     * @param logoSize
     * @throws Exception
     */
    private static void insertImage(BufferedImage qrBi, String imgPath, int logoSize) throws Exception {
        // 判断嵌入的文件是否存在
        File file = new File(imgPath);
        if (!file.exists()) {
            throw new RuntimeException("" + imgPath + "   该文件不存在!");
        }

        // 读取嵌入的图片
        Image imgSource = ImageIO.read(new File(imgPath));
        int width = imgSource.getWidth(null);
        int height = imgSource.getHeight(null);

        // 压缩LOGO
        if (width > logoSize) {
            width = logoSize;
        }
        if (height > logoSize) {
            height = logoSize;
        }
        Image image = imgSource.getScaledInstance(width, height, Image.SCALE_SMOOTH);
        BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = tag.getGraphics();
        g.drawImage(image, 0, 0, null); // 绘制缩小后的图
        g.dispose();
        imgSource = image;

        // 插入LOGO
        Graphics2D graph = qrBi.createGraphics();
        int x = (qrBi.getWidth() - width) / 2;
        int y = (qrBi.getHeight() - height) / 2;
        graph.drawImage(imgSource, x, y, width, height, null);
        Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();
    }

    /**
     * 生成二维码(嵌入图片)
     * @param content 二维码携带文本内容
     * @param logoFilePath 嵌入图片路径
     * @param qrPath  二维码图片生成文件
     * @throws Exception
     */
    public static void createQRCode(String content, int qcSize,  String logoFilePath, int logoSize, String qrPath) throws Exception {
        //1. 生成二维码图片
        BufferedImage image = QRCodeUtil.createImage(content,qcSize);
        //2. 二维码图片中嵌入logo
        insertImage(image, logoFilePath,logoSize);
        //3. 图片写入磁盘
        ImageIO.write(image, "png", new File(qrPath));
    }

    /**
     * 生成二维码图片(不包含图片)
     * @param content 二维码携带文本内容
     * @param qcSize 二维码大小
     * @param qrPath 生成的二维码文件全路径名
     * @throws Exception
     */
    public static void createQRCode(String content, int qcSize ,String qrPath) throws Exception{
        BufferedImage image = QRCodeUtil.createImage(content,qcSize);
        ImageIO.write(image, "png", new File(qrPath));

    }

    /**
     * 解析二维码
     *
     * @param file 二维码图片
     * @return 二维码携带内容
     * @throws Exception
     */
    public static String parseQRCode(File file) throws Exception {
        BufferedImage image;
        image = ImageIO.read(file);
        if (image == null) {
            return null;
        }
        BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        Result result;
        HashMap<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
        hints.put(DecodeHintType.CHARACTER_SET, CHARSET_UTF8);
        result = new MultiFormatReader().decode(bitmap, hints);
        String resultStr = result.getText();
        return resultStr;
    }

    /**
     * 解析二维码
     *
     * @param path 二维码所在路径
     * @return 二维码携带文本内容
     * @throws Exception
     */
    public static String parseQRCode(String path) throws Exception {
        return QRCodeUtil.parseQRCode(new File(path));
    }
}

2. 测试用例

import org.junit.Test;
import org.zongf.learn.qrcoder.QRCodeUtil;

/**
 * @Description:
 * @author: zongf
 * @date: 2019-02-26 16:17
 */
public class TestQRCodeUtil {

    //不包含图片的二维码生成路径
    private static String qr1 = "qr_001.jpg";

    //包含图片的二维码生成路径
    private static String qr2 = "qr_002.jpg";

    /** 二维码携带内容 */
    private static String qrContent = "http://www.baidu.com";


    //测试生成不包含图片的二维码
    @Test
    public void createQRWithOutLogo() throws Exception{
        QRCodeUtil.createQRCode(qrContent, 200, qr1);
        System.out.println("不包含图片的二维码已经生成...\n**************************\n");
    }

    //测试包含图片的二维码
    @Test
    public void createQRIncludeLogo() throws Exception{
        QRCodeUtil.createQRCode(qrContent, 200, "logo.png", 50, qr2);
        System.out.println("包含图片的二维码已经生成...\n**************************\n");
    }

    // 解析不带图片的二维码
    @Test
    public void parseQRWithOutLogo() throws Exception{
        String result = QRCodeUtil.parseQRCode(qr1);
        System.out.println("不包含图片的二维码解析结果:" + result + "\n**************************\n");
    }

    // 解析带图片的二维码
    @Test
    public void parseQRIncludeLogo() throws Exception{
        String result = QRCodeUtil.parseQRCode(qr1);
        System.out.println("包含图片的二维码解析结果:" + result + "\n**************************\n");
    }
}

猜你喜欢

转载自blog.csdn.net/zongf0504/article/details/87941448