zxing生成二维码

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

 

package com.test;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.sun.org.apache.xml.internal.security.utils.Base64;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;

//Component注解添加,其余需要使用的类就可以使用@Autowired对工具类自动装配
@Component
public class QRCodeUtil {
    /**
     * 生成Base64 二维码
     */
    public String crateQRCode(String content) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            QRCodeWriter writer = new QRCodeWriter();
            BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, 200, 200);
            BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
            ImageIO.write(bufferedImage, "png", os);
            //添加图片格式标识
            return new String("data:image/png;base64," + Base64.encode(os.toByteArray()));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            os.close();
        }
        return null;
    }

    public static void main(String[] args) throws Exception {
        //String qrCode = new QRCodeUtil().crateQRCode(new String("测试生成二维码".getBytes(), "ISO-8859-1"));
        //String qrCode = new QRCodeUtil().crateQRCode("https://www.baidu.com");
        //System.out.println(qrCode);
        //1.二维码中的信息
        String content = "https://www.baidu.com";
        //2.通过zxing生成二维码(保存到本地图片,支持以data url的形式体现)
        QRCodeWriter writer = new QRCodeWriter();
        //参数1:二维码信息;参数2:图片类型;参数3:宽度;参数4:长度
        BitMatrix bt = writer.encode(content, BarcodeFormat.QR_CODE, 200, 200);
        //保存二维码到本地
        Path path = new File("C:\\Users\\admin\\Desktop\\test.png").toPath();
        MatrixToImageWriter.writeToPath(bt,"png",path);
    }
}

 

posted @ 2020-12-27 16:24  lost_s  阅读(127)  评论(0编辑  收藏  举报