java通用二维码生成工具封装

该工具类使用google.zxing实现二维码生成

可生成通用二维码和带中心图标的二维码


import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.HashMap;

import javax.imageio.ImageIO;

import org.apache.log4j.Logger;

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

public class QRUtil {
    
    private static Logger log = Logger.getLogger(QRUtil.class);
    
    //定义二维码宽度
    private static final int width = 300;
    //定义二维码高度
    private static final int height = 300;
    //定义二维码图片格式
    private static final String format = "png";
    private static final int BLACK = 0xFF000000;//用于设置图案的颜色 
    private static final int WHITE = 0xFFFFFFFF;//用于背景色
    
    
    /**
     * 将二维码内容生成通用二维码
     * 记得删除临时文件
     * @param qrContent
     * @param fileName
     * @return
     * @throws Exception
     */
    public static File generateQR(String qrContent, String fileName) throws Exception{
        log.info("QRUtil: start generate qrCode...");
        //定义二维码的参数
        HashMap hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        hints.put(EncodeHintType.MARGIN, 2);

        //生成二维码
        BitMatrix bitMatrix = new MultiFormatWriter().encode(qrContent, BarcodeFormat.QR_CODE, width, height);
        //二维码删除白边
        bitMatrix = deleteWhite(bitMatrix);
        //创建临时文件
        File file = File.createTempFile(fileName, ".png");
        Path path = file.toPath();
        MatrixToImageWriter.writeToPath(bitMatrix, format, path);
        return file;
    }
    
    /**
     * 将二维码内容和小图标logo
     * 记得删除临时文件
     * @param qrContent
     * @param fileName
     * @param is
     * @return
     * @throws Exception
     */
    public static File generateQR(String qrContent, String fileName, InputStream logoIs)throws Exception{
        log.info("QRUtil: start generate qrCode...");
        //定义二维码的参数
        HashMap hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        hints.put(EncodeHintType.MARGIN, 2);

        //生成二维码
        BitMatrix bitMatrix = new MultiFormatWriter().encode(qrContent, BarcodeFormat.QR_CODE, width, height);
        //二维码删除白边
        bitMatrix = deleteWhite(bitMatrix);
        //创建临时文件
        File file = File.createTempFile(fileName, ".png");
        //创建文件缓存
        BufferedImage bufferedImage = toBufferedImage(bitMatrix);
        //小图标写入二维码
        dealIcon(bufferedImage, logoIs);
        ImageIO.write(bufferedImage, format, file);
        return file;
    }
    
    /**
     * BitMatrix转换成BufferedImage
     * @param matrix
     * @return
     */
    private 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));
            }
        }
        return image;
    }
    
    /**
     * 小图标写入二维码
     * @param matrixImage
     * @param logoIs
     * @throws IOException
     */
    private static void dealIcon(BufferedImage matrixImage, InputStream logoIs) throws IOException {
        Graphics2D g2 = matrixImage.createGraphics();
        int matrixWidth = matrixImage.getWidth(); 
        int matrixHeigh = matrixImage.getHeight(); 
        // 读取logo图片
        BufferedImage logo = ImageIO.read(logoIs);
        //开始绘制图片
        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();
    }
    
    /**
     * 二维码删除白边
     * @param matrix
     * @return
     */
    private static BitMatrix deleteWhite(BitMatrix matrix) {
        int[] rec = matrix.getEnclosingRectangle();
        int resWidth = rec[2] + 1;
        int resHeight = rec[3] + 1;

        BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
        resMatrix.clear();
        for (int i = 0; i < resWidth; i++) {
            for (int j = 0; j < resHeight; j++) {
                if (matrix.get(i + rec[0], j + rec[1]))
                    resMatrix.set(i, j);
            }
        }
        return resMatrix;
    }

}

 

你可能感兴趣的:(Java-工具封装)