码迷,mamicode.com
首页 > 移动开发 > 详细

Android下利用zxing类库实现扫一扫

时间:2015-07-27 22:41:06      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:

程序源代码及可执行文件下载地址:http://files.cnblogs.com/rainboy2010/zxingdemo.zip

zxing,一款无比强大的条码解析类库,下面讲解一下如何利用zxing类库实现扫一扫功能,先放上一张效果图:

技术分享

主要代码如下:

1.在onPreviewFrame方法里获取预览图像,然后传递给DecodeHandler去解析

 public void onPreviewFrame(byte[] data, Camera camera) 
  {
    Point cameraResolution = configManager.getCameraResolution();
    if (!useOneShotPreviewCallback) 
    {
      camera.setPreviewCallback(null);
    }
    if (previewHandler != null) 
    {
      Message message = previewHandler.obtainMessage(previewMessage, cameraResolution.x,cameraResolution.y, data);
      message.sendToTarget();
      previewHandler = null;
    } 
    else 
    {
      Log.d(TAG, "Got preview callback, but no handler for it");
    }
  }

2. 在decode方法里调用zxing类库对图像进行解析

private void decode(byte[] data, int width, int height)
  {
    long start = System.currentTimeMillis();
    Result rawResult = null;
    
    byte[] rotatedData = new byte[data.length];
    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++)
            rotatedData[x * height + height - y - 1] = data[x + y * width];
    }
    int tmp = width; // Here we are swapping, that‘s the difference to #11
    width = height;
    height = tmp;
    
    PlanarYUVLuminanceSource source = CameraManager.get().buildLuminanceSource(rotatedData, width, height);
    BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
    try 
    {
      rawResult = multiFormatReader.decodeWithState(bitmap);
    } catch (ReaderException re) {
      // continue
    } finally {
      multiFormatReader.reset();
    }

    if (rawResult != null) 
    {
      long end = System.currentTimeMillis();
      Log.d(TAG, "Found barcode (" + (end - start) + " ms):\n" + rawResult.toString());
      Message message = Message.obtain(activity.getHandler(), R.id.decode_succeeded, rawResult);
      Log.d(TAG, "Sending decode succeeded message...");
      message.sendToTarget();
    } 
    else 
    {
      Message message = Message.obtain(activity.getHandler(), R.id.decode_failed);
      message.sendToTarget();
    }
  }

 

Android下利用zxing类库实现扫一扫

标签:

原文地址:http://www.cnblogs.com/rainboy2010/p/4681199.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!