Java代码生成二维码

  • Post author:
  • Post category:java




Java代码生成二维码:

背景:在项目的需求中,大部分会需要你写一个生成二维码的功能,二维码里面存储特定的信息

示例:

pom.xml依赖:

<!--    Zxing-->
    <dependency>
      <groupId>com.google.zxing</groupId>
      <artifactId>core</artifactId>
      <version>3.0.0</version>
    </dependency>
    <dependency>
      <groupId>com.google.zxing</groupId>
      <artifactId>javase</artifactId>
      <version>3.0.0</version>
    </dependency>

测试:

package com.zking.ssm.service.impl;

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 javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 许缘
 * @company xxx公司
 * @create 2022-10-10  21:14
 */
public class test {
    public static void main(String[] args) throws WriterException, IOException {
        //core.3.3.jar Zxing
        //创建一个‘画者’
        MultiFormatWriter mfw = new MultiFormatWriter();
        //内容,类型,宽度,高度,其他信息map
        String content = "许缘写的二维码";
        BarcodeFormat type = BarcodeFormat.QR_CODE;
        int width = 600;
        int height = 600;
        Map map = new HashMap();
        map.put(EncodeHintType.CHARACTER_SET,"UTF-8");
        map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
        map.put(EncodeHintType.MARGIN,2);
        //画一个虚拟的二维码对象
        BitMatrix matrix = mfw.encode(content,type,width,height,map);
        //流虚拟二维码对象的信息写入文件
        int black = Color.black.getRGB();
        int white = Color.white.getRGB();
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
        for (int x= 0;x<width;x++){
            for (int y =0;y<height;y++){
                image.setRGB(x,y,matrix.get(x,y)?black:white);
            }
        }
        File file = new File("D:\\sucai\\test.jpg");
        ImageIO.write(image,"jpg",file);

    }
}

生成的二维码:

在这里插入图片描述



版权声明:本文为weixin_63719049原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。