Java生成二维码常用的两种方式: - Google的ZXing - Denso公司的QRCode 至于两者的区别自行百度,这里介绍使用ZXing生成解析二维码
前期准备
添加ZXing依赖Jar包
<!--ZXing 二维码 --> <dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.3.0</version> </dependency> <dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>3.3.0</version> </dependency>
|
ZXing生成二维码
public static void createQRCode(String content, File destPath) { int width = 300; int height = 300; String format = "png"; HashMap hashMap = new HashMap(); hashMap.put(EncodeHintType.CHARACTER_SET, "utf-8");
hashMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); hashMap.put(EncodeHintType.MARGIN, 2); try { BitMatrix matrix = new MultiFormatWriter() .encode(content, BarcodeFormat.QR_CODE, width, height, hashMap); MatrixToImageWriter.writeToPath(matrix, format, destPath.toPath()); } catch (Exception e) { e.printStackTrace(); } }
|
ZXing解析二维码
public static void readQRCode(File destPath) { try { BufferedImage read = ImageIO.read(destPath); BinaryBitmap binaryBitmap = new BinaryBitmap (new HybridBinarizer(new BufferedImageLuminanceSource(read))); HashMap hashMap = new HashMap<>(); hashMap.put(EncodeHintType.CHARACTER_SET, "utf-8"); Result result = new MultiFormatReader().decode(binaryBitmap, hashMap); System.out.println("二维码格式:" + result.getBarcodeFormat()); System.out.println("二维码内容:" + result.getText()); } catch (Exception e) { e.printStackTrace(); } }
|
使用方法
public static void main(String[] args) { String content = "https://www.itze.cn"; File file = new File("D:\\123.png"); createQRCode(content, file); readQRCode(file); }
|
解析结果
解析其他的二维码也是可以的,实测解析微信个人二维码也是可以的。