您的位置:首页 > 移动开发 > Android开发

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

2015-07-27 21:01 591 查看
程序源代码及可执行文件下载地址: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();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: