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”