ZXing生成二维码(Java)

ZXing生成二维码

说明:生成二维码需要用到zxing的jar包,可以去资源包下载zxing-3.3.0.jar,在项目中引入即可。

生成二维码最常用的格式为QRcode(因为此格式支持中文且专利开放),因此该项目就创建QRcode格式的二维码,也可包含中文。

import java.io.File;
import java.util.HashMap;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

/**
 * ZXing生成二维码
 *
 */
public class CreateQRCode {
    private int width;      // 宽
    private int height;     // 高
    private String format;  // 格式
    private String content; // 内容
    private String filePath;// 文件生产路径
    private HashMap hints;  // 配置参数

    // 链接、图片格式、宽、高、存储路径
    public CreateQRCode(String content, String format, int width, int height, String filepath) {
        this.content = content;
        this.format = format;
        this.width = width;
        this.height = height;
        this.filePath = filepath;

        init();
    }

    public void init(){

        // 定义二维码参数
        hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);  // 容错率,就是在二维码破坏下能否正常使用,H较高
        hints.put(EncodeHintType.MARGIN, 2); // 边距

        // 生成二维码
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            MatrixToImageWriter.writeToPath(bitMatrix, format, new File(filePath).toPath());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

主函数调用

public class Main{ 
    public static void main(String[] args) {
        new CreateQRCode("http://www.sina.com", "png", 300, 300, "D:/img.png");
    }

}

生成结果,可在传递参数的路径下查看,这里是“D:\img.png”

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值