使用Google Zxing生成的二维码扫描后₹符号变为?的问题求助
解决二维码生成中₹符号扫描后变为?的问题
问题出在二维码生成时未指定UTF-8字符编码,导致多字节的₹符号被错误编码,扫描解码后显示为?。ZXing的QRCodeWriter默认编码规则不保证支持所有Unicode字符,需要手动指定UTF-8编码提示。
修改后的代码如下:
import com.google.zxing.BarcodeFormat; import com.google.zxing.WriterException; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; import com.google.zxing.EncodeHintType; import java.nio.file.Path; import java.nio.file.Paths; import java.io.IOException; import java.util.HashMap; import java.util.Map; public boolean generateQRCode(String qrCodeContent, String filePath, int width, int height) { try { QRCodeWriter qrCodeWriter = new QRCodeWriter(); // 指定UTF-8编码,确保特殊字符正确编码 Map<EncodeHintType, Object> hints = new HashMap<>(); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); BitMatrix bitMatrix = qrCodeWriter.encode(qrCodeContent, BarcodeFormat.QR_CODE, width, height, hints); Path path = Paths.get(filePath); MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path); return true; } catch (WriterException | IOException e) { log.error("Exception occurred while generating QR Code", e); } return false; }
修改说明
- 添加
EncodeHintType.CHARACTER_SET提示,明确指定字符编码为UTF-8,确保₹这类Unicode特殊字符被正确写入二维码。 - 导入所需的
EncodeHintType和Map、HashMap类。
内容的提问来源于stack exchange,提问作者samar taj Shaikh
相关产品推荐
相关产品推荐

