ZXing 生成或读取二维码(解决中文乱码的问题)
时间: 2024-03-21 14:40:07 浏览: 31
ZXing 是一个开源的条码和二维码扫描库,支持生成和读取二维码。为了解决中文乱码的问题,可以使用 UTF-8 编码进行处理。
生成二维码:
```java
String contents = "你好,世界!";
int width = 300;
int height = 300;
Hashtable<EncodeHintType, String> hints = new Hashtable<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, hints);
BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);
```
在生成二维码时,需要将字符集设置为 UTF-8,以避免中文乱码。
读取二维码:
```java
BufferedImage image = ImageIO.read(new File("qrcode.png"));
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Hashtable<DecodeHintType, String> hints = new Hashtable<>();
hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
Result result = new MultiFormatReader().decode(bitmap, hints);
String contents = result.getText();
```
在读取二维码时,同样需要将字符集设置为 UTF-8,以正确解码中文字符。