生成二维码工具类

<!--生成二维码 start-->
<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
</dependency>
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>3.4.0</version>
</dependency>

<!--生成二维码 end-->

注意:根据需要自己配置,输出二维码的本地路径


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;
import com.honey.track.constant.BaseFileConstant;
import org.springframework.util.StringUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author zxl
 */
public class BarcodeUtils {
    /**
     * 二维码颜色 默认是黑色
     */
    private static final int QRCOLOR = 0xFF000000;
    /**
     * 背景颜色
     */
    private static final int BGWHITE = 0xFFFFFFFF;
    /**
     * 二维码宽
     */
    private static final int WIDTH = 256;
    /**
     * 二维码高
     */
    private static final int HEIGHT = 256;
    /**
     * 加文字二维码高
     */
    private static final int WORDHEIGHT = 270;

    public static boolean createQrImg(String fileName, String content) {
        boolean flag = false;
        try {
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);

            // 图片输出路径 根据需要自己配置输出路径
            String localPath = BaseFileConstant.StaticPath.getLocPath(BaseFileConstant.StaticPath.STATIC_QR);

            Path path = Paths.get(localPath, fileName);
            // Path path = Paths.get(BaseConstant.FILE_UPLOAD_QR_PATH, fileName);

            try {
                if (!Files.exists(path.getParent())) {
                    Files.createDirectories(path.getParent());
                }
                if (!Files.exists(path)) {
                    Files.createFile(path);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 输出二维码图片到文件夹
            MatrixToImageWriter.writeToPath(bitMatrix, "png", path);
            flag = true;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * encode 用于设置QR二维码参数
     */
    private static Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() {
        private static final long serialVersionUID = 1L;

        {
            // 设置QR二维码的纠错级别(H为最高级别)具体级别信息
            put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            // 设置编码方式
            put(EncodeHintType.CHARACTER_SET, "utf-8");
            put(EncodeHintType.MARGIN, 0);
        }
    };

    /**
     * 设置 Graphics2D 属性 (抗锯齿)
     *
     * @param graphics2D
     */
    private static void setGraphics2D(Graphics2D graphics2D) {
        graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        graphics2D.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
        Stroke s = new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);
        graphics2D.setStroke(s);
    }

    /**
     * 生成二维码图片存储到filePath中 单纯生成二维码
     *
     * @param content
     *            二维码内容 例如 xxx=12345601
     * @param filePath
     *            成二维码图片保存路径
     * @return
     */
    public static boolean createImg(String content, String filePath) {
        boolean flag = false;
        try {
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
            // 图片输出路径
            // 设备编号
            String code = content.split("=")[1];
            Path path = Paths.get(filePath + "//" + code + ".png");
            try {
                if (!Files.exists(path.getParent())) {
                    Files.createDirectories(path.getParent());
                }
                if (!Files.exists(path)) {
                    Files.createFile(path);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            // 输出二维码图片到文件夹
            MatrixToImageWriter.writeToPath(bitMatrix, "png", path);
            flag = true;

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 把带logo的二维码下面加上文字
     *
     * @param image
     * @param words
     * @return
     */
    private static BufferedImage insertWords(BufferedImage image, String words) {
        // 新的图片,把带logo的二维码下面加上文字
        if (!StringUtils.isEmpty(words)) {
            // 创建一个带透明色的BufferedImage对象
            BufferedImage outImage = new BufferedImage(WIDTH, WORDHEIGHT, BufferedImage.TYPE_INT_ARGB);
            Graphics2D outg = outImage.createGraphics();
            setGraphics2D(outg);
            // 画二维码到新的面板
            outg.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
            // 画文字到新的面板
            Color color = new Color(183, 183, 183);
            outg.setColor(color);
            // 字体、字型、字号
            outg.setFont(new Font("微软雅黑", Font.PLAIN, 18));
            // 文字长度
            int strWidth = outg.getFontMetrics().stringWidth(words);
            // 总长度减去文字长度的一半 (居中显示)
            int wordStartX = (WIDTH - strWidth) / 2;
            // height + (outImage.getHeight() - height) / 2 + 12
            int wordStartY = HEIGHT + 10;
            // 画文字
            outg.drawString(words, wordStartX, wordStartY);
            outg.dispose();
            outImage.flush();
            return outImage;

        }
        return null;
    }

    /**
     * @param logoFile
     *            loge图片的路径
     * @param contents
     *            二维码内容
     * @description 生成带logo的二维码图片 二维码下面带文字
     */
    public static void drawLogoQRCode(File logoFile, String contents) {
        try {
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            // 参数顺序分别为:编码内容,编码类型,生成图片宽度,生成图片高度,设置参数
            BitMatrix bm = multiFormatWriter.encode(contents, 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);
                }
            }
            // 把logo画到二维码上面
            if (Objects.nonNull(logoFile) && logoFile.exists()) {
                // 构建绘图对象
                Graphics2D g = image.createGraphics();
                setGraphics2D(g);
                // 读取Logo图片
                BufferedImage logo = ImageIO.read(logoFile);
                // 开始绘制logo图片 等比缩放:(width * 2 / 10 height * 2 / 10)不需缩放直接使用图片宽高
                // width * 2 / 5 height * 2 / 5 logo绘制在中心点位置
                // g.drawImage(logo, WIDTH * 2 / 5, HEIGHT * 2 / 5, logo.getWidth(), logo.getHeight(), null);
                g.drawImage(logo, WIDTH * 2 / 5, HEIGHT * 2 / 5, WIDTH * 2 / 10, HEIGHT * 2 / 10, null);
                g.dispose();
                logo.flush();

            }

            File codeFile = new File(logoFile.getParent());
            if (!codeFile.exists()) {
                codeFile.mkdirs();
            }
            // 设备编号
            String code = contents.split("=")[1];

            codeFile = new File(logoFile.getParent() + "/QrCode/", code + ".png");
            String parent = codeFile.getParent();
            File file = new File(parent);
            if (!file.exists()) {
                file.mkdirs();
            }

            if (!codeFile.exists()) {
                codeFile.createNewFile();
            }
            ImageIO.write(image, "png", codeFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param logoFile
     *            loge图片的路径
     * @param codeFile
     *            图片输出路径
     * @param qrUrl
     *            二维码内容
     * @param words
     *            二维码下面的文字
     * @description 生成带logo的二维码图片 二维码下面带文字
     */
    public static void drawLogoAndWordQRCode(File logoFile, File codeFile, String qrUrl, String words) {
        try {
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            // 参数顺序分别为:编码内容,编码类型,生成图片宽度,生成图片高度,设置参数
            BitMatrix bm = multiFormatWriter.encode(qrUrl, 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);
                }
            }

            // 把logo画到二维码上面
            if (Objects.nonNull(logoFile) && logoFile.exists()) {
                // 构建绘图对象
                Graphics2D g = image.createGraphics();
                setGraphics2D(g);
                // 读取Logo图片
                BufferedImage logo = ImageIO.read(logoFile);
                // 开始绘制logo图片 等比缩放:(width * 2 / 10 height * 2 / 10)不需缩放直接使用图片宽高
                // width * 2 / 5 height * 2 / 5 logo绘制在中心点位置
                g.drawImage(logo, WIDTH * 2 / 5, HEIGHT * 2 / 5, WIDTH * 2 / 10, HEIGHT * 2 / 10, null);
                g.dispose();
                logo.flush();
            }

            // 新的图片,把带logo的二维码下面加上文字
            image = insertWords(image, words);
            image.flush();
            Path path = codeFile.toPath();
            try {
                if (!Files.exists(path.getParent())) {
                    Files.createDirectories(path.getParent());
                }
                if (!Files.exists(path)) {
                    Files.createFile(path);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            ImageIO.write(image, "png", codeFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 

Java生成二维码工具类的源码是一段用Java语言编写的程序代码,用于生成二维码图片。下面是一个简单的Java生成二维码工具类的源码示例: ```java import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import com.google.zxing.BarcodeFormat; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; public class QRCodeGenerator { public static void main(String[] args) { String text = "https://www.example.com"; // 要生成二维码的内容 int width = 300; // 二维码图片的宽度 int height = 300; // 二维码图片的高度 String format = "png"; // 二维码图片的格式 try { BufferedImage image = generateQRCode(text, width, height); saveImage(image, format, "qrcode.png"); System.out.println("二维码生成。"); } catch (Exception e) { e.printStackTrace(); } } // 生成二维码图片 public static BufferedImage generateQRCode(String text, int width, int height) throws Exception { QRCodeWriter qrCodeWriter = new QRCodeWriter(); BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height); int matrixWidth = bitMatrix.getWidth(); BufferedImage image = new BufferedImage(matrixWidth, matrixWidth, BufferedImage.TYPE_INT_RGB); image.createGraphics(); Graphics2D graphics = (Graphics2D) image.getGraphics(); graphics.setColor(Color.WHITE); graphics.fillRect(0, 0, matrixWidth, matrixWidth); graphics.setColor(Color.BLACK); for (int i = 0; i < matrixWidth; i++) { for (int j = 0; j < matrixWidth; j++) { if (bitMatrix.get(i, j)) { graphics.fillRect(i, j, 1, 1); } } } return image; } // 保存二维码图片 public static void saveImage(BufferedImage image, String format, String filePath) throws IOException { ImageIO.write(image, format, new File(filePath)); } } ``` 这个工具类使用了Google的ZXing库来生成二维码。主要包含两个方法:`generateQRCode()`用于生成二维码图片,`saveImage()`用于保存二维码图片到文件。 使用时,只需要指定要生成二维码的内容、图片的宽度和高度,然后调用`generateQRCode()`方法获取生成二维码图片,最后保存到文件即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值