这是生成位图的简单易用的功能!我仅使用ZXing1.3.jar!我还将“校正级别”设置为“高”!
PS:x和y颠倒了,这很正常,因为bitMatrix颠倒了x和y。此代码与正方形图像完美配合。
public static Bitmap generateQrCode(String myCodeText) throws WriterException {
Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
QRCodeWriter qrCodeWriter = new QRCodeWriter();
int size = 256;
ByteMatrix bitMatrix = qrCodeWriter.encode(myCodeText,BarcodeFormat.QR_CODE, size, size, hintMap);
int width = bitMatrix.width();
Bitmap bmp = Bitmap.createBitmap(width, width, Bitmap.Config.RGB_565);
for (int x = 0; x < width; x++) {
for (int y = 0; y < width; y++) {
bmp.setPixel(y, x, bitMatrix.get(x, y)==0 ? Color.BLACK : Color.WHITE);
}
}
return bmp;
}
编辑
将bitmap.setPixels(...)与像素int数组一起使用比使用bitmap.setPixel一对一地更快:
BitMatrix bitMatrix = writer.encode(inputValue, BarcodeFormat.QR_CODE, size, size);
int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
pixels[offset + x] = bitMatrix.get(x, y) ? BLACK : WHITE;
}
}
bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);