JAVA 二维码生成和添加文字


    com.google.zxing
    core
    3.4.0


    com.google.zxing
    javase
    3.4.0

package com.xxx.utils;

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.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.xxx.entity.UserPo;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class QrCodeUtil {

    private static final Log log = LogFactory.getLog(QrCodeUtil.class);

    private static final QRCodeWriter QR_CODE_WRITER = new QRCodeWriter();

    // 设置默认参数,可以根据需要进行修改
    private static final int QRCOLOR = 0xFF000000; // 默认是黑色
    private static final int BGWHITE = 0xFFFFFFFF; // 背景颜色
    private static final int WIDTH = 180; // 二维码宽
    private static final int HEIGHT = 180; // 二维码高

    /**
     * 生成二维码字节数组.
     */
    public static byte[] generateQrCode(String text, String format, int width, int height) {
        try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            BitMatrix bitMatrix = QR_CODE_WRITER.encode(text, BarcodeFormat.QR_CODE, width, height);
            MatrixToImageWriter.writeToStream(bitMatrix, format, os);
            return os.toByteArray();
        } catch (WriterException e) {
            throw new RuntimeException(String.format("fail to generate qr code:text[%s]", text), e);
        } catch (IOException e) {
            throw new RuntimeException(String.format("fail to writeToStream when generating qr code: text[%s]", text), e);
        }
    }

    /**
     * 保存二维码图片到文件系统.
     */
    public static void generateQrCodeAndSave(String text, String format, int width, int height, String path) {
        try {
            BitMatrix bitMatrix = QR_CODE_WRITER.encode(text, BarcodeFormat.QR_CODE, width, height);
            MatrixToImageWriter.writeToPath(bitMatrix, format, Paths.get(path));
        } catch (WriterException e) {
            throw new RuntimeException(String.format("fail to generate qr code:text[%s]", text), e);
        } catch (IOException e) {
            throw new RuntimeException(String.format("fail to writeToStream when generating qr code: text[%s]", text), e);
        }
    }

    /**
     * 用于设置QR二维码参数
     * com.google.zxing.EncodeHintType:编码提示类型,枚举类型
     * EncodeHintType.CHARACTER_SET:设置字符编码类型
     * EncodeHintType.ERROR_CORRECTION:设置误差校正
     * ErrorCorrectionLevel:误差校正等级,L = ~7% correction、M = ~15% correction、Q = ~25% correction、H = ~30% correction
     * 不设置时,默认为 L 等级,等级不一样,生成的图案不同,但扫描的结果是一样的
     * EncodeHintType.MARGIN:设置二维码边距,单位像素,值越小,二维码距离四周越近
     * */
    private static Map hints = new HashMap() {
        private static final long serialVersionUID = 1L;
        {
            put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);// 设置QR二维码的纠错级别(H为最高级别)具体级别信息
            put(EncodeHintType.CHARACTER_SET, "utf-8");// 设置编码方式
            put(EncodeHintType.MARGIN, 0);
        }
    };

    public static BufferedImage createQr(UserPo po, Font font) throws WriterException{
        String content = po.getExtend1();
        String sampleCode = po.getExtend2();
        String sampleName = po.getExtend3();
        /**
         * MultiFormatWriter:多格式写入,这是一个工厂类,里面重载了两个 encode 方法,用于写入条形码或二维码
         *      encode(String contents,BarcodeFormat format,int width, int height,Map hints)
         *      contents:条形码/二维码内容
         *      format:编码类型,如 条形码,二维码 等
         *      width:码的宽度
         *      height:码的高度
         *      hints:码内容的编码类型
         * BarcodeFormat:枚举该程序包已知的条形码格式,即创建何种码,如 1 维的条形码,2 维的二维码 等
         * BitMatrix:位(比特)矩阵或叫2D矩阵,也就是需要的二维码
         */
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        /**参数顺序分别为:编码内容,编码类型,生成图片宽度,生成图片高度,设置参数
         * BitMatrix 的 get(int x, int y) 获取比特矩阵内容,指定位置有值,则返回true,将其设置为前景色,否则设置为背景色
         * BufferedImage 的 setRGB(int x, int y, int rgb) 方法设置图像像素
         *      x:像素位置的横坐标,即列
         *      y:像素位置的纵坐标,即行
         *      rgb:像素的值,采用 16 进制,如 0xFFFFFF 白色
         */
        BitMatrix bm = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
        // 创建一个图片缓冲区存放二维码图片
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        // 开始利用二维码数据创建Bitmap图片,分别设为黑(0xFFFFFFFF)白(0xFF000000)两色
        for (int x = 0; x < WIDTH; x++) {
            for (int y = 0; y < HEIGHT; y++) {
                image.setRGB(x, y, bm.get(x, y) ? QRCOLOR : BGWHITE);
            }
        }
        int height = image.getHeight();
// ------------------------------------------自定义文本描述-------------------------------------------------
        if (!StringUtils.isEmpty(sampleCode)) {
            // 1、在内存创建图片缓冲区 这里设置画板的宽高和类型
            BufferedImage outImage = new BufferedImage(500, 180, BufferedImage.TYPE_4BYTE_ABGR);

            // 2、创建画布,获取图像对象
            Graphics2D outg = outImage.createGraphics();

            // 3、抗锯齿,防止模糊
            RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            rh.put(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
            rh.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
            outg.setRenderingHints(rh);

            // 4、在画布上画上二维码 X轴Y轴,宽度高度(X轴贴最右侧 500 - WIDTH)
            outg.drawImage(image, 500 - WIDTH, 0, image.getWidth(), image.getHeight(), null);

            // 设置文字颜色为黑色
            outg.setColor(Color.BLACK);
            // 字体、字型、字号
            outg.setFont(font);

            // 获取字体宽度
            int codeWidth = outg.getFontMetrics().stringWidth(sampleCode);
            int nameWidth = outg.getFontMetrics().stringWidth(sampleName);

            // drawString(文字信息、x轴、y轴)方法根据参数设置文字的坐标轴 ,根据需要来进行调整
            outg.drawString("样品编号: " + sampleCode, 20, 30);
            outg.drawString("样品名称: " + sampleName, 20, 60);
            outg.drawString("样品状态: □收样完好  □待检", 20, 90);
            outg.drawString("□在检  □已检  □留样", 20, 120);
            //  例: outg.drawString(depatmentName,  65 - strWidth / 2, height + (outImage.getHeight() - height) / 2 - h3); 根据需求自行计算需要的宽高

            outg.dispose();
            outImage.flush();
            image = outImage;
        }
        image.flush();
        return image;

    }

    public static void drawLogoQRCode() {
        UserPo po = new UserPo();
        po.setUserId(UUID.randomUUID().toString());
        po.setExtend1(po.getUserId());
        po.setExtend2("ZS001");
        po.setExtend3("张三");

        FileOutputStream fileOutputStream = null;

        try {
            // 保存路径输出流,将图片输出到指定路径
            fileOutputStream = new FileOutputStream("D:" + File.separator + "var" + File.separator + po.getUserId() + ".png");
            Font fontChinese = new Font("黑体", Font.PLAIN, 18);
            BufferedImage image = createQr(po, fontChinese);

            boolean createQRCode = ImageIO.write(image, "png", fileOutputStream);

        } catch (WriterException | IOException e) {
            log.error("二维码写入IO流异常", e);
        } finally {
            try {
                if (null != fileOutputStream){
                    fileOutputStream.flush();
                    fileOutputStream.close();
                }
            } catch (IOException ioe){
                log.error("二维码关流异常", ioe);
            }
        }
    }

    private static final String QR_CODE_IMAGE_PATH = "D:\\var\\hello world.png";

    public static void test1() throws Exception {
        // QrCodeUtil.generateQrCodeAndSave("hello world", "png", 350, 350, QR_CODE_IMAGE_PATH);
        byte[] b = QrCodeUtil.generateQrCode("29B09FCD-65DC-4FCD-A4A4-6E79E7A2F56C", "png", 350, 350);
        ByteArrayInputStream stream = new ByteArrayInputStream(b);
        BufferedImage img = ImageIO.read(stream);
        try {
            File file = new File("D:\\var\\hello world.png");
            ImageIO.write(img, "png", file);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            stream.close();
        }
    }

    public static void test2() throws Exception {
        QrCodeUtil.generateQrCodeAndSave("hello world", "png", 350, 350, QR_CODE_IMAGE_PATH);
    }

    public static void main(String[] args) throws Exception {
        // test1();
        // test2();
        drawLogoQRCode();
    }
}

二维码.png

你可能感兴趣的:(JAVA 二维码生成和添加文字)