Google开源工具Zxing 之 生成二维码

1,项目地址:https://github.com/zxing/zxing

2,引入依赖(对应的链接可以下载jar包)

    <!--二维码 操作依赖-->
        <!-- https://mvnrepository.com/artifact/com.google.zxing/core -->
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.3.3</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.google.zxing/javase -->
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>javase</artifactId>
            <version>3.3.3</version>
        </dependency>

3,效果

(1)带颜色:

 

(2)普通:

 

 

(3)模拟微信:

 

 4,util类

GenrateTwoDimensionalCode :主要操作类
package com.mangoubiubiu.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

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.Hashtable;

/***
 * ZXING二维码生成类
 */
public class GenrateTwoDimensionalCode {
    // 需要注意 颜色码需是16进制字符串
    private static final int HUA_SE = 0xFFF0F8FF; // 码颜色
    private static final int DI_SE = 0xFFEE82EE; // 底色

   // 二维码输出路径
    private static final String PATH="E:/";
   //二维码后缀名
    private static final String FORMAT = "jpg";
    //二维码宽度
    private static final int WIDTH = 400;
    //二维码高度
    private static final int HEIGHT = 400;

    /**
     *颜色
     * @param url:存入二维码的url
     * @param jpgName:图片名字
     * @return
     * @throws WriterException
     * @throws IOException
     */
    public static boolean generateCodeByUrl(String msg, String jpgName) throws WriterException, IOException {

        // 设置编码,防止中文乱码
        Hashtable<EncodeHintType, Object> ht = new Hashtable<EncodeHintType, Object>();
        ht.put(EncodeHintType.CHARACTER_SET, "UTF-8");

        // 设置二维码参数(编码内容,编码类型,图片宽度,图片高度,格式)
        BitMatrix bitMatrix = new MultiFormatWriter().encode(msg, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, ht);
        // 生成二维码(定义二维码输出服务器路径)
        File outputFile = new File(PATH);
        if (!outputFile.exists()) {
            // 创建文件夹
            outputFile.mkdir();
        }

        int b_width = bitMatrix.getWidth();
        int b_height = bitMatrix.getHeight();
        // 建立图像缓冲器
        BufferedImage image = new BufferedImage(b_width, b_height, BufferedImage.TYPE_3BYTE_BGR);
        for (int x = 0; x < b_width; x++) {
            for (int y = 0; y < b_height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? HUA_SE : DI_SE);
            }
        }
        // 生成二维码
        ImageIO.write(image, FORMAT, new File(PATH + "/" + jpgName + "." + FORMAT));


        return true;
    }

    /**
     *普通
     * @param msg:二维码带的信息
     * @param jpgName:二维码名字
     */
    public static void  generateCodeByMsg(  String msg,String jpgName){
        final String content = msg;
        //定义二维码的参数
        HashMap hints = new HashMap();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        hints.put(EncodeHintType.MARGIN, 2);
        //生成二维码
        try{
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);

            Path file = new File(PATH + "/" + jpgName + "." + FORMAT).toPath();
            MatrixToImageWriter.writeToPath(bitMatrix, FORMAT, file);
        }catch(Exception e){
            e.printStackTrace();
        }
    }


    /**
     *带头像
     * @param msg:二维码带的信息
     * @param jpgName:二维码名字
     * @throws IOException
     * @throws WriterException
     */
    public static void generateCodeByTxMsg(String msg,String jpgName) throws IOException, WriterException{

        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
        // 指定纠错等级,纠错级别(L 7%、M 15%、Q 25%、H 30%)
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        // 内容所使用字符集编码
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
//      hints.put(EncodeHintType.MAX_SIZE, 350);//设置图片的最大值
//      hints.put(EncodeHintType.MIN_SIZE, 100);//设置图片的最小值
        hints.put(EncodeHintType.MARGIN, 1);//设置二维码边的空度,非负数

        BitMatrix bitMatrix = new MultiFormatWriter().encode(msg,//要编码的内容
                //编码类型,目前zxing支持:Aztec 2D,CODABAR 1D format,Code 39 1D,Code 93 1D ,Code 128 1D,
                //Data Matrix 2D , EAN-8 1D,EAN-13 1D,ITF (Interleaved Two of Five) 1D,
                //MaxiCode 2D barcode,PDF417,QR Code 2D,RSS 14,RSS EXPANDED,UPC-A 1D,UPC-E 1D,UPC/EAN extension,UPC_EAN_EXTENSION
                BarcodeFormat.QR_CODE,
                WIDTH, //条形码的宽度
                HEIGHT, //条形码的高度
                hints);//生成条形码时的一些配置,此项可选

        // 生成二维码
        File outputFile = new File(PATH + "/" + jpgName + "." + FORMAT);//指定输出路径

        MyMatrixToImageWriter.writeToFile(bitMatrix, FORMAT, outputFile);
    }


}
MyMatrixToImageWriter:生产条形码的基类 
package com.mangoubiubiu.util;
import com.google.zxing.common.BitMatrix;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;



/**
 * 二维码的生成需要借助MatrixToImageWriter类,该类是由Google提供的,可以将该类直接拷贝到源码中使用,当然你也可以自己写个
 * 生产条形码的基类
 */
public class MyMatrixToImageWriter {
    private static final int BLACK = 0xFF000000;//用于设置图案的颜色
    private static final int WHITE = 0xFFFFFFFF; //用于背景色

    private MyMatrixToImageWriter() {
    }

    public static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.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,  (matrix.get(x, y) ? BLACK : WHITE));
//              image.setRGB(x, y,  (matrix.get(x, y) ? Color.YELLOW.getRGB() : Color.CYAN.getRGB()));
            }
        }
        return image;
    }

    public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        //设置logo图标
        LogoConfig logoConfig = new LogoConfig();
        image = logoConfig.LogoMatrix(image);

        if (!ImageIO.write(image, format, file)) {
            throw new IOException("Could not write an image of format " + format + " to " + file);
        }else{
            System.out.println("图片生成成功!");
        }
    }

    public static void writeToStream(BitMatrix matrix, String format, OutputStream stream) throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        //设置logo图标
        LogoConfig logoConfig = new LogoConfig();
        image = logoConfig.LogoMatrix(image);

        if (!ImageIO.write(image, format, stream)) {
            throw new IOException("Could not write an image of format " + format);
        }
    }
}
LogoConfig:头像配置类
package com.mangoubiubiu.util;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
/**
 * 二维码 添加 logo图标 处理的方法,
 * 模仿微信自动生成二维码效果,有圆角边框,logo和二维码间有空白区,logo带有灰色边框
 * @author Administrator sangwenhao
 *
 */
public class LogoConfig {


    /**
     * 设置 logo
     * @param matrixImage 源二维码图片
     * @return 返回带有logo的二维码图片
     * @throws IOException
     * @author Administrator sangwenhao
     */
    public BufferedImage LogoMatrix(BufferedImage matrixImage) throws IOException{



        /**
         * 读取二维码图片,并构建绘图对象
         */
        Graphics2D g2 = matrixImage.createGraphics();

        int matrixWidth = matrixImage.getWidth();
        int matrixHeigh = matrixImage.getHeight();

        /**
         * 读取Logo图片
         */
        BufferedImage logo = ImageIO.read(new File("E:\\tx.png"));

        //开始绘制图片
        g2.drawImage(logo,matrixWidth/5*2,matrixHeigh/5*2, matrixWidth/5, matrixHeigh/5, null);//绘制
        BasicStroke stroke = new BasicStroke(5,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND);
        g2.setStroke(stroke);// 设置笔画对象
        //指定弧度的圆角矩形
        RoundRectangle2D.Float round = new RoundRectangle2D.Float(matrixWidth/5*2, matrixHeigh/5*2, matrixWidth/5, matrixHeigh/5,20,20);
        g2.setColor(Color.white);
        g2.draw(round);// 绘制圆弧矩形

        //设置logo 有一道灰色边框
        BasicStroke stroke2 = new BasicStroke(1,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND);
        g2.setStroke(stroke2);// 设置笔画对象
        RoundRectangle2D.Float round2 = new RoundRectangle2D.Float(matrixWidth/5*2+2, matrixHeigh/5*2+2, matrixWidth/5-4, matrixHeigh/5-4,20,20);
        g2.setColor(new Color(128,128,128));
        g2.draw(round2);// 绘制圆弧矩形

        g2.dispose();
        matrixImage.flush() ;
        return matrixImage ;
    }

}

 

感谢:

https://www.cnblogs.com/lixuwu/p/5953226.html

https://blog.csdn.net/weixin_39309402/article/details/78545903

     

posted @ 2020-08-24 23:40  KwFruit  阅读(397)  评论(0编辑  收藏  举报