gpt4 book ai didi

java - 使用zxing进行二维码编解码

转载 作者:IT老高 更新时间:2023-10-28 20:53:02 24 4
gpt4 key购买 nike

好的,所以我要排除这里有人以前使用过 zxing 的机会。我正在开发一个 Java 应用程序,它需要做的一件事就是将一个字节数组的数据编码为一个二维码,然后在稍后对其进行解码。

这是我的编码器的示例:

byte[] b = {0x48, 0x45, 0x4C, 0x4C, 0x4F};
//convert the byte array into a UTF-8 string
String data;
try {
data = new String(b, "UTF8");
}
catch (UnsupportedEncodingException e) {
//the program shouldn't be able to get here
return;
}

//get a byte matrix for the data
ByteMatrix matrix;
com.google.zxing.Writer writer = new QRCodeWriter();
try {
matrix = writer.encode(data, com.google.zxing.BarcodeFormat.QR_CODE, width, height);
}
catch (com.google.zxing.WriterException e) {
//exit the method
return;
}

//generate an image from the byte matrix
int width = matrix.getWidth();
int height = matrix.getHeight();

byte[][] array = matrix.getArray();

//create buffered image to draw to
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

//iterate through the matrix and draw the pixels to the image
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int grayValue = array[y][x] & 0xff;
image.setRGB(x, y, (grayValue == 0 ? 0 : 0xFFFFFF));
}
}

//write the image to the output stream
ImageIO.write(image, "png", outputStream);

此代码中的开始字节数组仅用于测试它。实际的字节数据会有所不同。

这是我的解码器的样子:

//get the data from the input stream
BufferedImage image = ImageIO.read(inputStream);

//convert the image to a binary bitmap source
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

//decode the barcode
QRCodeReader reader = new QRCodeReader();

Result result;
try {
result = reader.decode(bitmap, hints);
} catch (ReaderException e) {
//the data is improperly formatted
throw new MCCDatabaseMismatchException();
}

byte[] b = result.getRawBytes();
System.out.println(ByteHelper.convertUnsignedBytesToHexString(result.getText().getBytes("UTF8")));
System.out.println(ByteHelper.convertUnsignedBytesToHexString(b));

convertUnsignedBytesToHexString(byte) 是一种将字节数组转换为十六进制字符串的方法。

当我尝试同时运行这两个代码块时,输出如下:

48454c4c4f
202b0b78cc00ec11ec11ec11ec11ec11ec11ec

显然文本正在被编码,但数据的实际字节完全关闭。任何帮助将不胜感激。

最佳答案

所以,对于那些不想花两天时间在互联网上搜索来弄清楚这一点的人来说,为了将来引用,当你将字节数组编码成二维码时,你必须使用 ISO-8859-1字符集,而不是 UTF-8

关于java - 使用zxing进行二维码编解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2489048/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com