Хорошо, таким образом, я собираюсь взять от шанса, что кто-то здесь использовал zxing прежде. Я разрабатываю JAVA-приложение и одну из вещей, которые она должна сделать, кодируют массив байтов данных в QR-код и затем декодируют его в более позднее время.
Вот пример того, на что похож мой кодер:
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
Очевидно текст кодируется, но фактические байты данных абсолютно выключены. Любая справка ценилась бы здесь.
Итак, для справки в будущем для тех, кто не хочет тратить два дня на поиск в Интернете, чтобы понять это, когда вы кодируете массивы байтов в QR-коды, вы должны использовать ISO-8859-1
набор символов, а не UTF-8
.
Если вам действительно нужно кодировать UTF-8, вы можете попробовать добавить пометку порядка байтов Unicode. Я понятия не имею, насколько широко поддерживается этот метод, но ZXing, по крайней мере, похоже, поддерживает его: http://code.google.com/p/zxing/issues/detail?id= 103
Я недавно читал о режиме QR, и я думаю , что я видел ту же самую практику, упомянутую в другом месте, но я не знаю, где именно.