前言
QR Code码,是由Denso公司于1994年9月研制的一种矩阵二维码符号,它具有一维条码及其它二维条码所具有的信息容量大、可靠性高、可表示汉字及图象多种文字信息、保密防伪性强等优点。(from baidu.com)
说明
该工具类提供二维码生成、logo图片插入、二维码解析、多张二维码打包压缩等方法。
生成二维码:
private static BufferedImage createImage(String content, String imgPath,
boolean needCompress, String productName) throws Exception {
Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);
int width = bitMatrix.getWidth();
int height = bitMatrix.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, bitMatrix.get(x, y) ? 0xFF000000
: 0xFFFFFFFF);
}
}
if (imgPath == null || "".equals(imgPath)) {
return image;
}
// 插入图片
QRCodeUtils.insertImage(image, imgPath, needCompress, productName);
return image;
}
解析二维码
/**
* 解析二维码
*
* @param file 二维码图片
* @return
* @throws Exception
*/
public static String decode(File file) throws Exception {
BufferedImage image;
image = ImageIO.read(file);
if (image == null) {
return null;
}
BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(
image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result;
Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
result = new MultiFormatReader().decode(bitmap, hints);
String resultStr = result.getText();
return resultStr;
}
二维码压缩打包:
/***
* 二维码打包
**/
@Test
public void zipFiles() throws Exception {
List<File> fileList = new ArrayList<>();
String text = "java大神!"; //这里设置自定义网站url
// String logoPath = "C:\\Users\\Pictures\\lingxi.png";
String destPath = "C:\\Users\\Pictures\\erweima";
QRCodeUtils.mkOrClearDir(destPath);
File file111 = QRCodeUtils.encode("图片名称111", text, null, destPath, true, "巡检路线1-站点1");
File file222 = QRCodeUtils.encode("图片名称2222", text, null, destPath, true, "巡检路线1-站点2");
System.out.println(file111.getPath());
System.out.println(file222.getPath());
fileList.add(file111);
fileList.add(file222);
String url = destPath + "二维码.zip";
File zipFile = new File(url);
// 调用压缩方法
ZipMultiFileUtil.zipFiles(fileList.stream().toArray(File[]::new), zipFile);
//将项目名称的文件夹 压缩为zip
boolean flag = ZipMultiFileUtil.fileToZip(destPath, destPath, "二维码.zip");
System.out.println("二维码压缩结果:" + flag);
System.out.println("二维码压缩包地址:" + url);
}
单元测试:
/***
* 二维码生成
**/
@Test
public void QRCreateImage() throws Exception {
String text = "javaer!"; //这里设置自定义网站url
// String logoPath = "C:\\Users\\Pictures\\lingxi.png";
String destPath = "C:\\Users\\Pictures\\";
File file111 = QRCodeUtils.encode("图片名称111", text, null, destPath, true, "巡检路线");
System.out.println(file111.getPath());
}