Java 生成二维码实战
点击上方“码农突围”,马上关注
这里是码农充电第一站,回复“666”,获取一份专属大礼包
真爱,请设置“星标”或点个“在看”
ZXing
是一个开源 Java 类库用于解析多种格式的 1D/2D 条形码。目标是能够对QR编码、Data Matrix、UPC的1D条形码进行解码。其提供了多种平台下的客户端包括:J2ME、J2SE和Android。<dependency>
<groupId>com.google.zxinggroupId>
<artifactId>coreartifactId>
<version>3.3.0version>
dependency>
<dependency>
<groupId>com.google.zxinggroupId>
<artifactId>javaseartifactId>
<version>3.3.0version>
dependency>
1. com.google.zxing.MultiFormatWriter
根据内容以及图像编码参数生成图像2D矩阵。2. com.google.zxing.client.j2se.MatrixToImageWriter
根据图像矩阵生成图片文件或图片缓存 BufferedImage
。
public void encode(String content, String filepath) throws WriterException, IOException {
int width = 100;
int height = 100;
MapObject> encodeHints = new HashMapObject>();
encodeHints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, encodeHints);
Path path = FileSystems.getDefault().getPath(filepath);
MatrixToImageWriter.writeToPath(bitMatrix, "png", path);
}
解析二维码图片
javax.imageio.ImageIO
读取图片文件,并存为一个 java.awt.image.BufferedImage
对象。java.awt.image.BufferedImage
转换为 ZXing 能识别的com.google.zxing.BinaryBitmap
对象。3. com.google.zxing.MultiFormatReader
根据图像解码参数来解析com.google.zxing.BinaryBitmap
。public String decode(String filepath) throws IOException, NotFoundException {
BufferedImage bufferedImage = ImageIO.read(new FileInputStream(filepath));
LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
Binarizer binarizer = new HybridBinarizer(source);
BinaryBitmap bitmap = new BinaryBitmap(binarizer);
HashMapObject> decodeHints = new HashMapObject>();
decodeHints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
Result result = new MultiFormatReader().decode(bitmap, decodeHints);
return result.getText();
}
(完)
码农突围资料链接
1、卧槽!字节跳动《算法中文手册》火了,完整版 PDF 开放下载!
2、计算机基础知识总结与操作系统 PDF 下载
3、艾玛,终于来了!《LeetCode Java版题解》.PDF
4、Github 10K+,《LeetCode刷题C/C++版答案》出炉.PDF欢迎添加鱼哥个人微信:smartfish2020,进粉丝群或围观朋友圈
评论