【Android QR Code】开源项目:ZXing(三)二维码解码

继续上一节的内容

本节我们将对上一节的QQ群号二维码进行解码

QQ群号二维码图片另存为后,将下载的.jpg拷贝到项目assets目录下

 

1、解码配置

Map<DecodeHintType,Object> hints = new EnumMap<DecodeHintType,Object>(DecodeHintType.class);
Collection<BarcodeFormat> decodeFormats = EnumSet.noneOf(BarcodeFormat.class);
decodeFormats.addAll(EnumSet.of(BarcodeFormat.QR_CODE));
hints.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats);
hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");

配置需要解码的图片格式为二维码,字符集编码为UTF-8

 

2、加载图片

private BinaryBitmap loadImage(String fileName, Context context) throws IOException {
    Bitmap bitmap = BitmapFactory.decodeStream(context.getResources().getAssets().open(fileName));
    
    int lWidth = bitmap.getWidth();
    int lHeight = bitmap.getHeight();
    int[] lPixels = new int[lWidth * lHeight];
    bitmap.getPixels(lPixels, 0, lWidth, 0, 0, lWidth, lHeight);
    return new BinaryBitmap(new HybridBinarizer(new RGBLuminanceSource(lWidth, lHeight, lPixels)));
}

首先,从assets目录下加载图片,编码为Android定义的位图Bitmap对象

然后,取得该图片的像素数据,存入整形数组中

最后,将图片的像素数据,转成ZXing定义的位图BinaryBitmap对象

类BinaryBitmap:This class is the core bitmap class used by ZXing to represent 1 bit data. Reader objects accept a BinaryBitmap and attempt to decode it.

注意:目前仅支持.jpg格式图片

 

3、解码

Result lResult = new MultiFormatReader().decode(loadImage(fileName, context), hints);
String lText = lResult.getText();

lText解码之后的字符串

 

运行结果:

posted on 2012-11-29 17:09  Anthony Li  阅读(6249)  评论(1编辑  收藏  举报

博客园博客已停止更新,博客地址:dyinigbleed.com