Java之二维码QR生成工具类

今天又遇到了生成二维码的问题,之前也遇到过没有记录,今天把用到的工具类记录一下。

直接上代码QRCodeImageUtil工具类

依赖

<!-- https://mvnrepository.com/artifact/com.google.zxing/javase -->
		<dependency>
		    <groupId>com.google.zxing</groupId>
		    <artifactId>javase</artifactId>
		    <version>3.4.0</version>
		</dependency>

代码

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
 
import javax.imageio.ImageIO;
 
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
 
/**
* @ClassName: QRCodeImageUtil
* @Description:二维码工具类
* @author 
* @date 
*/
public class QRCodeImageUtil {
	
	private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;
 
    private static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
            }
        }
        return image;
    }
 
    static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        if (!ImageIO.write(image, format, file)) {
            throw new IOException("Could not write an image of format " + format + " to " + file);
        }
    }
 
    static void writeToStream(BitMatrix matrix, String format, OutputStream stream) throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        if (!ImageIO.write(image, format, stream)) {
            throw new IOException("Could not write an image of format " + format);
        }
    }
	
	
	/**
    * @Title: createQrCode
    * @Description:生成二维码图片
    * @author weny.yang
    * @date Mar 26, 2021
    */
    public static String generateQRCodeImage(String url, String path, String fileName, int length) {
        try {
            Map<EncodeHintType, String> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, length, length, hints);
            File file = new File(path, fileName);
            if (file.exists() || ((file.getParentFile().exists() || file.getParentFile().mkdirs()) && file.createNewFile())) {
                writeToFile(bitMatrix, "jpg", file);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

延伸

GitHub上也有比较完善的QR二维码生成工具类,开箱即用,依赖如下

<!-- https://mvnrepository.com/artifact/com.github.binarywang/qrcode-utils-->
<dependency>
    <groupId>com.github.binarywang</groupId>
	<artifactId>qrcode-utils</artifactId>
	<version>1.3</version>
</dependency>

简单介绍一下

QrcodeUtils

//创建生成默认高度(400)的二维码图片可以指定是否贷logo
QrcodeUtils.createQrcode(content, logoFile);
//根据指定边长创建生成的二维码
QrcodeUtils.createQrcode(content, length, logoFile);
//解析二维码
QrcodeUtils.decodeQrcode(file);

不过生成的是byte[]数组,需要自己再生成file文件。也提供了decodeQrcode解码方法。

createQrcode方法测试demo,引入对应依赖,填好自己对应的logoFile和fileFullPath即可运行

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import com.github.binarywang.utils.qrcode.QrcodeUtils;

public class Test7 {

	public static void main(String[] args) {
	  //创建生成默认高度(400)的二维码图片可以指定是否贷logo
      String content = "https://spring.io/";
      File logoFile = new File("D:\\xxx\\spring-logo.jpg");//logo地址
      String fileFullPath = "D:\\xxx\\spring-qr.jpg";//生成二维码地址
      try {
		byte[] qrbytes = QrcodeUtils.createQrcode(content, logoFile);
		byte2file(qrbytes, fileFullPath);
	  } catch (Exception e) {
		e.printStackTrace();
	  }
	}
	
	/**
     * byte[]数组转File
     *
     * @param bytes
     * @param fileFullPath
     * @return
     */
    public static File byte2file(byte[] bytes, String fileFullPath) {
        if (bytes == null) {
            return null;
        }
        FileOutputStream fileOutputStream = null;
        try {
            File file = new File(fileFullPath);
            //判断文件是否存在
            if (file.exists()) {
                file.mkdirs();
            }
            fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(bytes);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            }  catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
        return null;
    }

}

生成二维码图片如下

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值