java 生成二维码图片/流

背景

最近做项目,遇到需要扫码跳转某些页面,获取返回某些文字的需求,经过收集调研后,选择google提供的封装方法,具体代码如下

依赖

引入google.zxing相关jar包依赖

<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.3.3</version>
</dependency>
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>3.3.3</version>
</dependency>

实体类(可跳过)

import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

@Data
public class QRCodeParams {

    private String txt;                //二维码内容
    private String qrCodeUrl;          //二维码网络路径
    private String filePath;           //二维码生成物理路径
    private String fileName;           //二维码生成图片名称(包含后缀名)
    private String logoPath;           //logo图片
    private Integer width = 300;           //二维码宽度
    private Integer height = 300;          //二维码高度
    private Integer onColor = 0xFF000000;  //前景色
    private Integer offColor = 0xFFFFFFFF; //背景色
    private Integer margin = 1;            //白边大小,取值范围0~4
    private ErrorCorrectionLevel level = ErrorCorrectionLevel.L;  //二维码容错率

    /**
     * 返回文件后缀名
     *
     * @return
     */
    public String getSuffixName() {
        String imgName = this.getFileName();
        if (StringUtils.isNotEmpty(imgName)) {
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
            return suffix;
        }else {
            return "";
        }
    }
}

具体方法

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageConfig;
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.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;

public class QRCodeGenerator {
    private static int width = 300;              //二维码宽度
    private static int height = 300;             //二维码高度
    private static int onColor = 0xFF000000;     //前景色
    private static int offColor = 0xFFFFFFFF;    //背景色
    private static final int margin = 1;         //白边大小,取值范围0~4
    private static ErrorCorrectionLevel level = ErrorCorrectionLevel.L;  //二维码容错率
    private static final String FORMAT = "png";  //默认后缀

    /**
     * 生成二维码
     *
     * @param params QRCodeParams属性:txt、fileName、filePath不得为空;
     */
    public static void generateQRImage(QRCodeParams params) {
        if (params == null || params.getFileName() == null || 
            params.getFilePath() == null || params.getTxt() == null) {
            throw new RuntimeException("参数错误");
        }
        try {
            initData(params);
            String imgPath = params.getFilePath();
            String imgName = params.getFileName();
            String txt = params.getTxt();
            if (params.getLogoPath() != null && !"".equals(params.getLogoPath().trim())) {
                generateQRImage(txt, params.getLogoPath(), imgPath, 
                                imgName, params.getSuffixName());
            } else {
                generateQRImage(txt, imgPath, imgName, params.getSuffixName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成二维码
     * @param txt     //二维码内容
     * @param imgPath //二维码保存物理路径
     * @param imgName //二维码文件名称
     * @param suffix  //图片后缀名
     */
    public static void generateQRImage(String txt, String imgPath, String imgName, String suffix) {
        File filePath = new File(imgPath);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        File imageFile = new File(imgPath, imgName);
        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
        // 指定纠错等级
        hints.put(EncodeHintType.ERROR_CORRECTION, level);
        // 指定编码格式
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.MARGIN, margin);   //设置白边
        try {
            MatrixToImageConfig config = new MatrixToImageConfig(onColor, offColor);
            BitMatrix bitMatrix = new MultiFormatWriter().encode(txt, BarcodeFormat.QR_CODE, width, height, hints);
//        	bitMatrix = deleteWhite(bitMatrix);
            MatrixToImageWriter.writeToPath(bitMatrix, suffix, imageFile.toPath(), config);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成二维码
     *
     * @param content //二维码内容
     */
    public static byte[] generate(String content) {
        byte[] result = null;
        ByteArrayOutputStream out = null;
        BufferedImage bufferedImage = null;
        try {
            out = new ByteArrayOutputStream();
            Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
            // 指定纠错等级
            hints.put(EncodeHintType.ERROR_CORRECTION, level);
            // 指定编码格式
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            hints.put(EncodeHintType.MARGIN, margin);   //设置白边
            // MatrixToImageConfig config = new MatrixToImageConfig(onColor, offColor);
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            bitMatrix = deleteWhite(bitMatrix);
            bufferedImage = toBufferedImage(bitMatrix);
            ImageIO.write(bufferedImage, FORMAT, out);
            result = out.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException("生成二维码失败", e);
        } finally {
            try {
                if (bufferedImage != null) {
                    bufferedImage.getGraphics().dispose();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
            }
        }
        return result;
    }


    /**
     * 生成带logo的二维码图片
     *
     * @param txt      //二维码内容
     * @param logoPath //logo绝对物理路径
     * @param imgPath  //二维码保存绝对物理路径
     * @param imgName  //二维码文件名称
     * @param suffix   //图片后缀名
     * @throws Exception
     */
    public static void generateQRImage(String txt, String logoPath, String imgPath, String imgName, String suffix) {
        File filePath = new File(imgPath);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        if (imgPath.endsWith("/")) {
            imgPath += imgName;
        } else {
            imgPath += "/" + imgName;
        }
        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, level);
        hints.put(EncodeHintType.MARGIN, margin);  //设置白边
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(txt, BarcodeFormat.QR_CODE, width, height, hints);
            File qrcodeFile = new File(imgPath);
            writeToFile(bitMatrix, suffix, qrcodeFile, logoPath);
        } catch (Exception e){
            throw new RuntimeException("操作失败");
        }

    }

    /**
     * @param matrix   二维码矩阵相关
     * @param format   二维码图片格式
     * @param file     二维码图片文件
     * @param logoPath logo路径
     * @throws IOException
     */
    public static void writeToFile(BitMatrix matrix, String format, File file, String logoPath) throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        Graphics2D gs = image.createGraphics();
        int ratioWidth = image.getWidth() * 2 / 10;
        int ratioHeight = image.getHeight() * 2 / 10;
        //载入logo
        Image img = ImageIO.read(new File(logoPath));
        int logoWidth = Math.min(img.getWidth(null), ratioWidth);
        int logoHeight = Math.min(img.getHeight(null), ratioHeight);
        int x = (image.getWidth() - logoWidth) / 2;
        int y = (image.getHeight() - logoHeight) / 2;
        gs.drawImage(img, x, y, logoWidth, logoHeight, null);
        gs.setColor(Color.black);
        gs.setBackground(Color.WHITE);
        gs.dispose();
        img.flush();
        if (!ImageIO.write(image, format, file)) {
            throw new IOException("Could not write an image of format " + format + " to " + file);
        }
    }

    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) ? onColor : offColor);
            }
        }
        return image;
    }

    public 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;
    }

    private static void initData(QRCodeParams params) {
        if (params.getWidth() != null) {
            width = params.getWidth();
        }
        if (params.getHeight() != null) {
            height = params.getHeight();
        }
        if (params.getOnColor() != null) {
            onColor = params.getOnColor();
        }
        if (params.getOffColor() != null) {
            offColor = params.getOffColor();
        }
        if (params.getLevel() != null) {
            level = params.getLevel();
        }

    }

    /**
     * 生成带logo的二维码图片
     *
     * @param txt      //二维码内容
     * @param logoPath //logo绝对物理路径
     * @throws Exception
     */
    public static byte[] generateQRImage(String txt, InputStream logoPath) throws Exception {
        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, level);
        hints.put(EncodeHintType.MARGIN, margin);  //设置白边
        BitMatrix bitMatrix = new MultiFormatWriter().encode(txt, BarcodeFormat.QR_CODE, width, height, hints);
        bitMatrix = deleteWhite(bitMatrix);
        return writeToFile(bitMatrix, logoPath);
    }

    /**
     * @param matrix   二维码矩阵相关
     * @param logoPath logo路径
     * @throws IOException
     */
    public static byte[] writeToFile(BitMatrix matrix, InputStream logoPath) {
        byte[] result = null;
        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            BufferedImage image = toBufferedImage(matrix);
            Graphics2D gs = image.createGraphics();
            int ratioWidth = image.getWidth() * 2 / 10;
            int ratioHeight = image.getHeight() * 2 / 10;
            //载入logo
            Image img = ImageIO.read(logoPath);
            int logoWidth = Math.min(img.getWidth(null), ratioWidth);
            int logoHeight = Math.min(img.getHeight(null), ratioHeight);
            int x = (image.getWidth() - logoWidth) / 2;
            int y = (image.getHeight() - logoHeight) / 2;
            gs.drawImage(img, x, y, logoWidth, logoHeight, null);
            gs.setColor(Color.black);
            gs.setBackground(Color.WHITE);
            gs.dispose();
            img.flush();
            ImageIO.write(image, FORMAT, out);
            result = out.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException("生成二维码失败", e);
        }
        return result;
    }


}

调用

// 生成二维码
QRCodeGenerator.generateQRImage("123","D:\\", "ewm_logo.jpg", "jpg");

// 生成带logo的二维码
QRCodeGenerator.generateQRImage("123", "C:\\Users\\20201236\\Pictures\\Saved Pictures\\小黑.png","D:\\", "ewm_logo.jpg", "jpg");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值