JAVA生成二维码工具类

91 阅读2分钟

依赖




<!-- 条形码、二维码生成 -->
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>2.2</version>
</dependency>
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>2.2</version>
</dependency>

代码



import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import sun.font.FontDesignMetrics;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Hashtable;

/**
 * 二维码的生成
 */

public class QRcreateUtile {


    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;

    private QRcreateUtile() {
    }

    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);
            }
        }
        return image;
    }

    public static void writeToFile(BitMatrix matrix, String format, File file)
            throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        if (!ImageIO.write(image, format, file)) {
            throw new IOException("Could not write an image of format "
                    + format + " to " + file);
        }
    }

    public static void writeToFileBgTransparentAndAddFont(BitMatrix matrix, String format, File file, String addText)
            throws IOException {
        BufferedImage image = toBufferedImage(matrix);

        image = QRcreateUtile.transparentImage(image, 10);

        QRcreateUtile.addFontImage(image, addText);

        if (!ImageIO.write(image, format, file)) {
            throw new IOException("Could not write an image of format "
                    + format + " to " + file);
        }
    }

    public static void writeToStream(BitMatrix matrix, String format,
                                     OutputStream stream) throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        if (!ImageIO.write(image, format, stream)) {
            throw new IOException("Could not write an image of format " + format);
        }
    }

    /**
     * 创建二维码
     * @param cardNoName
     * @param text
     * @param vcode
     * @param dirName
     * @throws WriterException
     * @throws IOException
     */
    public static File wirter2File(String cardNoName,String text,String vcode,String dirName) throws WriterException, IOException {

       //String text = "http://www.baidu.com"; // 二维码内容
       int width = 300; // 二维码图片宽度
       int height = 300; // 二维码图片高度
       String format = "png";// 二维码的图片格式

       Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
       hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 内容所使用字符集编码

       BitMatrix bitMatrix = new MultiFormatWriter().encode(text,
               BarcodeFormat.QR_CODE, width, height, hints);
       File directory = new File("");// 参数为空
       String courseFile = directory.getCanonicalPath();
       //System.out.println(courseFile);

        String path = courseFile + File.separator + "dir" + File.separator + vcode + File.separator + dirName + File.separator;
        File file = new File(path);
        if(!file.exists()){//如果文件夹不存在
            file.mkdir();//创建文件夹
        }
        // 生成二维码
        File outputFile = new File(   path + File.separator + cardNoName + ".png");
        outputFile.mkdirs();
        outputFile.createNewFile();
        QRcreateUtile.writeToFileBgTransparentAndAddFont(bitMatrix, format, outputFile, cardNoName);
        return outputFile;
   }

    /**
     * 设置图片背景透明
     * @param srcImage
     * @param alpha
     * @return
     */
    public static BufferedImage transparentImage(BufferedImage srcImage, int alpha) throws IOException {
        int imgHeight = srcImage.getHeight();//取得图片的长和宽
        int imgWidth = srcImage.getWidth();
        int c = srcImage.getRGB(3, 3);
        //防止越位
        if (alpha < 0) {
            alpha = 0;
        } else if (alpha > 10) {
            alpha = 10;
        }
        BufferedImage tmpImg = new BufferedImage(imgWidth + 10, imgHeight + 10, BufferedImage.TYPE_4BYTE_ABGR);//新建一个类型支持透明的BufferedImage
        for(int i = 0; i < imgWidth; ++i)//把原图片的内容复制到新的图片,同时把背景设为透明
        {
            for(int j = 0; j < imgHeight; ++j){
                //把背景设为透明
                if(srcImage.getRGB(i, j) == c){
                    tmpImg .setRGB(i, j, c & 0x00ffffff);
                }
                //设置透明度
                else{
                    int rgb = tmpImg .getRGB(i, j);
                    rgb = ((alpha * 255 / 10) << 24) | (rgb & 0x00ffffff);
                    tmpImg .setRGB(i, j, rgb);
                }
            }
        }

        return tmpImg ;
    }

    // 二维码尺寸
    private static final int QRCODE_SIZE = 300;
    // 字体大小
    private static final int FONT_SIZE = 18;

    /**
     * 添加 底部图片文字
     *
     * @param source      图片源
     * @param declareText 文字本文
     */
    private static void addFontImage(BufferedImage source, String declareText) throws IOException {
        BufferedImage textImage = strToImage(declareText, QRCODE_SIZE, 50);
        Graphics2D g2 = source.createGraphics();

        //开启文字抗锯齿
        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        int width = textImage.getWidth(null);
        int height = textImage.getHeight(null);

        Image src = textImage;
        g2.drawImage(src, 0, QRCODE_SIZE - 40, width, height, null);
        g2.dispose();
    }

    private static BufferedImage strToImage(String str, int width, int height) throws IOException {
        BufferedImage textImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = (Graphics2D)textImage.getGraphics();

        textImage = g2.getDeviceConfiguration()
                .createCompatibleImage(width, height, Transparency.TRANSLUCENT);
        g2.dispose();
        g2 = textImage.createGraphics();

        //开启文字抗锯齿
        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g2.setBackground(Color.WHITE);
        g2.setPaint(Color.BLACK);
        FontRenderContext context = g2.getFontRenderContext();
        Font font = new Font("微软雅黑", Font.PLAIN, FONT_SIZE);
        g2.setFont(font);
        LineMetrics lineMetrics = font.getLineMetrics(str, context);
        FontMetrics fontMetrics = FontDesignMetrics.getMetrics(font);
        float offset = (width - fontMetrics.stringWidth(str)) / 2;
        float y = (height + lineMetrics.getAscent() - lineMetrics.getDescent() - lineMetrics.getLeading()) / 2;

        g2.drawString(str, (int)offset, (int)y);

        return textImage;
    }

    public static void main(String[] args) throws IOException, WriterException {
        wirter2File("test","test","xxx" , "2021-11-11");
    }
}