Google的zxing实现二维码生成和解析

一、需要下载maven依赖包

        <!-- 		google.zxing生成二维码 -->
        <!-- https://mvnrepository.com/artifact/com.google.zxing/core -->
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.3.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.google.zxing/javase -->
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>javase</artifactId>
            <version>3.3.0</version>
        </dependency>

二、编写一个QRCodeUtil二维码生成和解析的实现类

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.io.OutputStream;
import java.util.Hashtable;
import java.util.Random;

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

public class QRCodeUtil {

    // 编码格式
    private static final String CHARSET = "utf-8";
    // 生成二维码图片的自定义后缀名
    private static final String FORMAT = "JPG";
    // 二维码尺寸  
    private static final int QR_CODE_SIZE = 300;
    // 二维码LOGO宽度  
    private static final int LOGO_WIDTH = 60;
    // 二维码LOGO高度  
    private static final int LOGO_HEIGHT = 60;
    // 生成二维码自定义文件名称
    private static final String QR_CODE_NAME = "QRCode";
    // 扫描二维码后访问地址
    public static final String ACCESS_URL = "http://www.baidu.com/";
    // 二维码LOGO文件目录
    public static final String LOGO_URL = "D:\\images\\android.png";
    // 二维码文件存放地址
    public static final String QR_CODE_URL = "D:\\images\\qrcode";
    // 可查看二维码图片的路径
    public static final String IMAGE_URL = "D:\\images\\qrcode\\";  
    
    public static void main(String[] args) throws Exception {
    	// 运行生成二维码
	// encode();
    	// 解析二维码,查看二维码的内容
    	// String content = decode("D:\\images\\qrcode\\QRCode.jpg");
    	// System.out.println(content); 打印出来的是:http://www.baidu.com/
	}

    /**
     * 生成二维码(内嵌LOGO) 
     * 调用者指定二维码文件名 
     * @throws Exception
     */
    public static String encode() throws Exception {
        String fileName = QR_CODE_NAME;
        fileName = fileName.substring(0, fileName.indexOf(".")>0?fileName.indexOf("."):fileName.length())
                + "." + FORMAT.toLowerCase();
        BufferedImage image = QRCodeUtil.createImage(ACCESS_URL, LOGO_URL, true);
        mkdirs(QR_CODE_URL);
        ImageIO.write(image, FORMAT, new File(QR_CODE_URL + File.separator + fileName));

        return IMAGE_URL + fileName;
    }

    /**
     *  生成二维码(内嵌LOGO) 
     *  内容例如:http://www.baidu.com/
     * @param content
     *  LOGO地址例如:D:\\images\\android.png           
     * @param logoPath
     *  存储地址例如:D:\\images\\qrcode         
     * @param destPath
     * @throws Exception
     */
    public static String encode(String content, String logoPath, String destPath) throws Exception {
        return QRCodeUtil.encode(content, logoPath, destPath, false);
    }

    /**
     *  生成二维码 
     *  内容
     * @param content
     *  存储地址           
     * @param destPath
     *  是否压缩LOGO          
     * @param isCompress
     * @throws Exception
     */
    public static String encode(String content, String destPath, boolean isCompress) throws Exception {
        return QRCodeUtil.encode(content, null, destPath, isCompress);
    }

    /**
     *  生成二维码 
     *  内容
     * @param content
     *  存储地址           
     * @param destPath
     * @throws Exception
     */
    public static String encode(String content, String destPath) throws Exception {
        return QRCodeUtil.encode(content, null, destPath, false);
    }

    /**
     *  生成二维码(内嵌LOGO)
     *  内容
     * @param content
     *  LOGO地址           
     * @param logoPath
     *  输出流            
     * @param output
     *  是否压缩LOGO          
     * @param isCompress
     * @throws Exception
     */
    public static void encode(String content, String logoPath, OutputStream output, boolean isCompress)
            throws Exception {
        BufferedImage image = QRCodeUtil.createImage(content, logoPath, isCompress);
        ImageIO.write(image, FORMAT, output);
    }

    /**
     *  生成二维码 
     *  内容
     * @param content
     *  输出流            
     * @param output
     * @throws Exception
     */
    public static void encode(String content, OutputStream output) throws Exception {
        QRCodeUtil.encode(content, null, output, false);
    }
    
    /**
     *  生成二维码(内嵌LOGO) 
     *  二维码文件名随机,文件名可能会有重复 
     *  内容
     * @param content
     *  LOGO地址          
     * @param logoPath
     *  存放目录            
     * @param destPath
     *  是否压缩LOGO            
     * @param isCompress
     * @throws Exception
     */
    public static String encode(String content, String logoPath, String destPath, boolean isCompress) throws Exception {
        BufferedImage image = QRCodeUtil.createImage(content, logoPath, isCompress);
        mkdirs(destPath);
        String fileName = new Random().nextInt(99999999) + "." + FORMAT.toLowerCase();
        ImageIO.write(image, FORMAT, new File(destPath + "/" + fileName));
        return fileName;
    }

    /**
     *  生成图片
     *  内容,比如放入一个http连接地址,扫码后访问该地址
     *  http://www,baidu.com/
     * @param content
     *  LOGO地址
     * @param logoPath
     *  生成二维码后存放的目录路径     
     * @param destPath
     *  是否压缩LOGO    
     * @param isCompress
     * @throws Exception
     */
    private static BufferedImage createImage(String content, String logoPath, boolean isCompress) throws Exception {
        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
        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, QR_CODE_SIZE, QR_CODE_SIZE,
                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);
            }
        }
        if (logoPath == null || "".equals(logoPath)) {
            return image;
        }
        // 插入图片  
        QRCodeUtil.insertImage(image, logoPath, isCompress);
        return image;
    }

    /**
     *  插入LOGO 
     *  二维码图片
     * @param source
     *  LOGO图片地址           
     * @param logoPath
     *  是否压缩        
     * @param isCompress
     * @throws Exception
     */
    private static void insertImage(BufferedImage source, String logoPath, boolean isCompress) throws Exception {
        File file = new File(logoPath);
        if (!file.exists()) {
            throw new Exception("logo file not found.");
        }
        Image src = ImageIO.read(new File(logoPath));
        int width = src.getWidth(null);
        int height = src.getHeight(null);
        if (isCompress) { // 压缩LOGO  
            if (width > LOGO_WIDTH) {
                width = LOGO_WIDTH;
            }
            if (height > LOGO_HEIGHT) {
                height = LOGO_HEIGHT;
            }
            Image image = src.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();
            src = image;
        }
        // 插入LOGO  
        Graphics2D graph = source.createGraphics();
        int x = (QR_CODE_SIZE - width) / 2;
        int y = (QR_CODE_SIZE - height) / 2;
        graph.drawImage(src, 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();
    }

    // 检测是否存在该目录,不存在则创建
    public static void mkdirs(String destPath) {
        File file = new File(destPath);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
    }
    
    /**
     *  解析二维码,查看二维码的内容
     *  二维码图片
     * @param file    
     * @return
     * @throws Exception
     */
    public static String decode(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;
        Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
        hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
        result = new MultiFormatReader().decode(bitmap, hints);
        String resultStr = result.getText();
        return resultStr;
    }
    
    /**
     *  解析二维码 
     *  二维码图片地址
     * @param qrCodePath   
     * @return
     * @throws Exception
     */
    public static String decode(String qrCodePath) throws Exception {
        return QRCodeUtil.decode(new File(qrCodePath));
    }
}
如果需要设置不一样的背景颜色二维码,只需要改动
createImage方法内
for (int x = 0; x < width; x++) {
     for (int y = 0; y < height; y++) {
          image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
     }
}
其中0xFF000000 : 0xFFFFFFFF的开头0xFF固定后面加上RGB的值
比如需要修改二维码为RGB颜色对照表中的SkyBlue 1颜色把0xFF000000  变为 0xFF 87CEFF就可以了
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值