項目中有需求使用zxing實現二維碼掃描,但是不想使用UI組件,所以將zxingcore重新編譯成jar,可引用到項目裏,把yuv數據送入掃描接口,實現二維碼掃描。
一、在項目裏引入zxingcore.jar(以Android studio工程爲例)
將zxingcore.jar放入app/libs文件夾下並引用進工程
app下build.gradle
implementation files('libs/zxingcore.jar')
二、新建DecodeUtil工具類
package com.cwang.utils.zxingutils;
import android.os.Build;
import android.util.Log;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.PlanarYUVLuminanceSource;
import com.google.zxing.ReaderException;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.interjoy.utils.systemutils.HardwareManager;
/**
* 二維碼掃描工具類
* Created by cwang on 2018/11/28.
*/
public class DecodeUtil {
private static String deviceModel = Build.MODEL;//讀取設備型號
private static QRCodeReader qrCodeReader;
/**
* 設置掃描區域
* @param data
* @param width
* @param height
* @return
*/
private static PlanarYUVLuminanceSource buildLuminanceSource(byte[] data, int width, int height) {
if (HardwareManager.isX5Dev(deviceModel) || HardwareManager.isX8Dev(deviceModel)) // 限制掃描區域
return new PlanarYUVLuminanceSource(data, width, height, width * 3 / 8, height * 3 / 8, width / 4, height / 4, false);
else // 直接返回整幅圖像的數據,而不計算聚焦框大小。
return new PlanarYUVLuminanceSource(data, width, height, 0, 0, width, height, false);
}
/**
* 二維碼檢測
*
* @param data YUV數據
* @param width YUV數據的寬度
* @param height YUV數據的高度
*/
public static void decode(byte[] data, int width, int height, DecodeCallbackInterface DecodeCallback) {
if (qrCodeReader == null) qrCodeReader = new QRCodeReader();
Result rawResult = null;
PlanarYUVLuminanceSource source = buildLuminanceSource(data, width, height);
if (source != null) {
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
try {
rawResult = qrCodeReader.decode(bitmap);
DecodeCallback.DecodeCallback(rawResult.getText());
} catch (ReaderException re) {
re.printStackTrace();
} finally {
qrCodeReader.reset();
}
}
}
/**
* 掃描結果回調
*/
public interface DecodeCallbackInterface {
void DecodeCallback(String CodeStr);
}
}
三、調用掃描二維碼函數
DecodeUtil.decode(data, frontCameraWidth, frontCameraHeight, new DecodeUtil.DecodeCallbackInterface() {
@Override
public void DecodeCallback(String CodeStr) {
Log.i(Tag, "二維碼掃描結果爲 = " + CodeStr);
}
});