二维码的生成工具

二维码的生成

方式一

首先导包

       <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.3.0</version>
        </dependency>
        <dependency>
            <groupId>com.vaadin.external.google</groupId>
            <artifactId>android-json</artifactId>
            <version>0.0.20131108.vaadin1</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>javase</artifactId>
            <version>3.3.2</version>
        </dependency>
    控制层的代码
  public static void main(String[] args) {
    int width = 300;
    int height = 300;
    String format = "png";
    // 二维码的连接(中文)
    String content = "www.zhongyi.com";

    //定义二维码参数
    HashMap hints = new HashMap();
    hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
    hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
    hints.put(EncodeHintType.MARGIN, 2);

    //生成二维码
    try {
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
        // 二维码生成的位置及名称
        Path file = new File("E:img.png").toPath();
        MatrixToImageWriter.writeToPath(bitMatrix, format, file);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

方式二

生成二维码的同时也生成logo文字
导包

   <!--二维码-->
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-mock</artifactId>
            <version>2.0.8</version>
        </dependency>
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>javase</artifactId>
            <version>3.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.3.2</version>
            <scope>compile</scope>
        </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 com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.commons.lang3.StringUtils;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class QrCodeCreateUtil {

    private static final int QR_COLOR = 0xFF000000; // 默认是黑色
    private static final int BG_WHITE = 0xFFFFFFFF; // 背景颜色

    private static final int WIDTH = 400;
    private static final int HEIGHT = 400;

    private static final String ADDRESS = "D:\\code\\";

    private static Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() {
        private static final long serialVersionUID = 1L;

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

    /**
     * 将二维码生成文件
     * @param url logo文件连接
     * @param code  生成二维码code
     * @param note  二维码文字
     * @return 文件
     */
    // 生成带logo的二维码图片
    public static MultipartFile drawLogoQRCode(String url, String code, String note) {
        MultipartFile multipartFile = null;
        try {
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            // 参数顺序分别为:编码内容,编码类型,生成图片宽度,生成图片高度,设置参数
            BitMatrix encode = multiFormatWriter.encode(code, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
            BufferedImage bufferedImage = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);

            // 开始利用二维码数据创建Bitmap图片,分别设为黑(0xFFFFFFFF)白(0xFF000000)两色
            for (int i = 0; i < WIDTH; i++) {
                for (int j = 0; j < HEIGHT; j++) {
                    bufferedImage.setRGB(i, j, encode.get(i, j) ? QR_COLOR : BG_WHITE);
                }
            }
            int width = bufferedImage.getWidth();
            int height = bufferedImage.getHeight();

            if (StringUtils.isNotBlank(url)) {
                // 构建绘图对象
                Graphics2D graphics = bufferedImage.createGraphics();
                // 读取logo图片
                URL urlfile = new URL(url);
                InputStream inStream = urlfile.openStream();
                BufferedImage logo = ImageIO.read(inStream);
                // 开始绘制logo图片
                graphics.drawImage(logo, width * 2 / 5, height * 2 / 5, width * 2 / 10, height * 2 / 10, null);
                graphics.dispose();
                logo.flush();
            }

            // 自定义文本描述
            if (StringUtil.isNotEmpty(note)) {
                bufferedImage = handleNote(bufferedImage, note, width, height);
            }
            // 创建输出流
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bufferedImage.flush();
            ImageIO.write(bufferedImage, "png", bos);
            // 写入指定文件夹
//            ImageIO.write(bufferedImage, "png", handleFileName());
            multipartFile = new MockMultipartFile("test.jpeg", "test.jpeg", "", bos.toByteArray());
        } catch (Exception e) {
            e.getMessage();
        }
        return multipartFile;
    }

    public static BufferedImage handleNote(BufferedImage bufferedImage, String note, int width, int height) {
        // 新的图片,把带logo的二维码下面加上文字
        BufferedImage outImage = new BufferedImage(400, 445, BufferedImage.TYPE_4BYTE_ABGR);
        Graphics2D outg = outImage.createGraphics();
        // 画二维码到新的面板
        outg.drawImage(bufferedImage, 0, 0, bufferedImage.getWidth(), bufferedImage.getHeight(), null);
        // 画文字到新的面板
        outg.setColor(Color.BLACK);
        // 字体、字型、字号
        outg.setFont(new Font("楷体", Font.BOLD, 30));
        int strWidth = outg.getFontMetrics().stringWidth(note);
        if (strWidth > 399) {
            //长度过长就截取前面部分
            // 长度过长就换行
            String note1 = note.substring(0, note.length() / 2);
            String note2 = note.substring(note.length() / 2, note.length());
            int strWidth1 = outg.getFontMetrics().stringWidth(note1);
            int strWidth2 = outg.getFontMetrics().stringWidth(note2);
            outg.drawString(note1, 200 - strWidth1 / 2, height + (outImage.getHeight() - height) / 2 + 12);
            BufferedImage outImage2 = new BufferedImage(400, 485, BufferedImage.TYPE_4BYTE_ABGR);
            Graphics2D outg2 = outImage2.createGraphics();
            outg2.drawImage(outImage, 0, 0, outImage.getWidth(), outImage.getHeight(), null);
            outg2.setColor(Color.BLACK);
            // 字体、字型、字号
            outg2.setFont(new Font("楷体", Font.BOLD, 30));
            outg2.drawString(note2, 200 - strWidth2 / 2, outImage.getHeight() + (outImage2.getHeight() - outImage.getHeight()) / 2 + 5);
            outg2.dispose();
            outImage2.flush();
            outImage = outImage2;
        } else {
            outg.drawString(note, 200 - strWidth / 2, height + (outImage.getHeight() - height) / 2 + 12); // 画文字
        }
        outg.dispose();
        outImage.flush();
        return outImage;
    }

    /**
     * 简单二维码生成
     * @param code 生成二维码参数
     */
    public static BitMatrix getCode(String code) {
        BitMatrix bitMatrix = null;
        try {
            bitMatrix = new MultiFormatWriter().encode(code, BarcodeFormat.QR_CODE, 200, 200, hints);
        } catch (WriterException e) {
            e.printStackTrace();
            log.error("生成二维码失败");
        }
        return bitMatrix;
    }

测试调用

uploadFile(QrCodeCreateUtil.drawLogoQRCode(dto.getLogo(), dto.getCode(), dto.getNote()), FolderConst.CODE);

样式结果
在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱上编程2705

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值