QRCodeUtils.java 7.45 KB
package cn.com.glsx.busassistant.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.swetake.util.Qrcode;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;

/**
 * @author hedong
 * @version V1.0
 * @Title: QRCodeUtils
 * @Description:
 * @Company: Didihu.com.cn
 * @Date 2021/9/16 13:53
 */
public class QRCodeUtils {

    private static final int WIDTH = 300; // 二维码宽度
    private static final int HEIGHT = 300; // 二维码高度
    private static final String FORMAT = "png"; // 二维码图片格式
    private static final String CHARSET = "UTF-8"; // 二维码编码格式
    private static final int LOGO_WIDTH = 100; // logo宽度
    private static final int LOGO_HEIGHT = 100; // logo高度

    /**
     * 生成二维码图片,并在中间加入logo
     *
     * @param content 二维码内容
     * @param inputStream logo文件流
     * @param outputStream   二维码图片输出文件流
     */
    public static void createQRCodeWithLogo(String content, InputStream inputStream, ByteArrayOutputStream outputStream) {
        try {
            // 1. 生成二维码图片
            QRCodeWriter writer = new QRCodeWriter();
            HashMap<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            hints.put(EncodeHintType.MARGIN, 1);
            BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
            BufferedImage qrImage = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
            for (int x = 0; x < WIDTH; x++) {
                for (int y = 0; y < HEIGHT; y++) {
                    qrImage.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
                }
            }

            // 2. 读取logo文件
            BufferedImage logoImage = ImageIO.read(inputStream);

            // 3. 在二维码中间加入logo
            Graphics2D g2d = qrImage.createGraphics();
            int x = (WIDTH - LOGO_WIDTH) / 2;
            int y = (HEIGHT - LOGO_HEIGHT) / 2;
            g2d.drawImage(logoImage, x, y, LOGO_WIDTH, LOGO_HEIGHT, null);
            // 画圆角矩形
            RoundRectangle2D round = new RoundRectangle2D.Float(x, y, LOGO_WIDTH, LOGO_HEIGHT, 6, 6);
            g2d.setColor(Color.WHITE);
            g2d.setStroke(new BasicStroke(3));
            g2d.draw(round);
            g2d.dispose();

            // 4. 输出二维码图片
            ImageIO.write(qrImage, FORMAT, outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public QRCodeUtils() {
    }

    public static void encoderQRCode(String content, String imgPath) throws Exception {
        encoderQRCode(content, (String)imgPath, "jpg", 7);
    }

    public static void encoderQRCode(String content, OutputStream output) throws Exception {
        encoderQRCode(content, (OutputStream)output, "jpg", 7);
    }

    public static void encoderQRCode(String content, String imgPath, String imgType) throws Exception {
        encoderQRCode(content, (String)imgPath, imgType, 7);
    }

    public static void encoderQRCode(String content, OutputStream output, String imgType) throws Exception {
        encoderQRCode(content, (OutputStream)output, imgType, 7);
    }

    public static void encoderQRCode(String content, String imgPath, String imgType, int version) throws Exception {
        BufferedImage bufImg = qRCodeCommon(content, imgType, version);
        File imgFile = new File(imgPath);
        ImageIO.write(bufImg, imgType, imgFile);
    }

    public static void encoderQRCode(String content, String imgPath, int width, int heigth) throws Exception {
        encoderQRCode(content, (String)imgPath, "jpg", 7, width, heigth);
    }

    public static void encoderQRCode(String content, String imgPath, int version, int width, int heigth) throws Exception {
        encoderQRCode(content, imgPath, "jpg", version, width, heigth);
    }

    public static void encoderQRCode(String content, OutputStream output, int width, int heigth) throws Exception {
        encoderQRCode(content, (OutputStream)output, "jpg", 7, width, heigth);
    }

    public static void encoderQRCode(String content, OutputStream output, String imgType, int version) throws Exception {
        BufferedImage bufImg = qRCodeCommon(content, imgType, version);
        ImageIO.write(bufImg, imgType, output);
    }

    public static void encoderQRCode(String content, String imgPath, String imgType, int version, int width, int heigth) throws Exception {
        BufferedImage bufImg = qRCodeCommon(content, imgType, version, width, heigth);
        File imgFile = new File(imgPath);
        ImageIO.write(bufImg, imgType, imgFile);
    }

    public static void encoderQRCode(String content, OutputStream output, String imgType, int version, int width, int heigth) throws Exception {
        BufferedImage bufImg = qRCodeCommon(content, imgType, version, width, heigth);
        ImageIO.write(bufImg, imgType, output);
    }

    private static BufferedImage qRCodeCommon(String content, String imgType, int version) throws Exception {
        int width = 67 + 12 * (version - 1);
        int height = 67 + 12 * (version - 1);
        return qRCodeCommon(content, imgType, version, width, height);
    }

    private static BufferedImage qRCodeCommon(String content, String imgType, int version, int width, int height) throws Exception {
        BufferedImage bufImg = null;

        try {
            Qrcode qrcodeHandler = new Qrcode();
            qrcodeHandler.setQrcodeErrorCorrect('M');
            qrcodeHandler.setQrcodeEncodeMode('B');
            qrcodeHandler.setQrcodeVersion(version);
            byte[] contentBytes = content.getBytes("utf-8");
            bufImg = new BufferedImage(width, height, 12);
            Graphics2D gs = bufImg.createGraphics();
            gs.setBackground(Color.WHITE);
            gs.clearRect(0, 0, width, height);
            gs.setColor(Color.BLACK);
            int pixoff = 0;
            if (contentBytes.length > 0 && contentBytes.length < 256) {
                boolean[][] s = qrcodeHandler.calQrcode(contentBytes);

                for(int i = 0; i < s.length; ++i) {
                    for(int j = 0; j < s.length; ++j) {
                        if (s[j][i]) {
                            gs.fillRect(j * 5 + pixoff, i * 5 + pixoff, 5, 5);
                        }
                    }
                }
//去掉边框
//                Rectangle2D mfRect = new Float();
//                mfRect.setRect(0.0D, 0.0D, (double)width, (double)height);
//                gs.setStroke(new BasicStroke(2.0F));
//                gs.draw(mfRect);
                gs.dispose();
                bufImg.flush();
                return bufImg;
            } else {
                throw new Exception("QRCode content bytes length = " + contentBytes.length + " not in [0, 256].");
            }
        } catch (Exception var13) {
            var13.printStackTrace();
            throw new Exception("QRCode generate exception:" + var13.getMessage(), var13);
        }
    }
}