当前位置:   article > 正文

java生成二维码

java生成二维码

1、引入pom依赖

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

2、生成二维码工具类

package com.web.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Component;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;

/**
 * 二维码生成
 */
@Component
public class QRCodeUtil {

    private static final String CHARSET = "utf-8";

    private static final int QRCODE_SIZE = 300;

    /**
     * 二维码生成
     *
     * @param content 二维码内容 必填
     * @param width 宽度 非必填 默认 300
     * @param height 高度 分必填 默认 300
     * @return
     */
    public static String getQRCode(String content,Integer width,Integer height) {
        if (ObjectUtils.isEmpty(width)){
            width = QRCODE_SIZE;
        }
        if (ObjectUtils.isEmpty(height)){
            height = QRCODE_SIZE;
        }
        HashMap map = new HashMap();
        map.put(EncodeHintType.CHARACTER_SET,CHARSET);
        // 字符编码为UTF-8
        map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        // 二维码空白区域,最小为0也有白边,只是很小,最小是6像素左右
        map.put(EncodeHintType.MARGIN, 0);
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = null;
        try {
            bitMatrix = qrCodeWriter.encode(content, 
                BarcodeFormat.QR_CODE,QRCODE_SIZE, QRCODE_SIZE,map);
        } catch (WriterException e) {
            throw new RuntimeException(e);
        }
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            MatrixToImageWriter.writeToStream(bitMatrix, "PNG", outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Base64.Encoder encoder = Base64.getEncoder();
        String text = encoder.encodeToString(outputStream.toByteArray());
        return "data:image/png;base64,"+text;
    }

}
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/编程冒险家/article/detail/60442
推荐阅读
相关标签
  

闽ICP备14008679号