如何使用ZXing库识别图像中的QR码?

时间:2017-03-22 09:37:52

标签: xamarin xamarin.android qr-code zxing

我有Xamarin Android项目,我想从相机识别QR码并同时将图片保存到存储。我使用Android.Hardware.Camera.IPreviewCallback从相机获取图像。保存图像按预期工作,但QR码识别失败。这是我的代码:

void Android.Hardware.Camera.IPreviewCallback.OnPreviewFrame(byte[] data, Android.Hardware.Camera camera)
{
    byte[] jpegData = ConvertYuvToJpeg(data);
    Bitmap bitmap = BytesToBitmap(jpegData);
    SaveBitmapImage(bitmap); // This works great


    var width = (int)_textureView.Width;
    var height = (int)_textureView.Height;

    // How to get LuminanceSource??
    //LuminanceSource source = new RGBLuminanceSource(rgbValues, bm.Width, bm.Height, RGBLuminanceSource.BitmapFormat.ARGB32);
    //LuminanceSource source = new RGBLuminanceSource( jpegData, width, height);
    LuminanceSource source = new PlanarYUVLuminanceSource(data, width, height, 
        0, 0, width, height, false);
    BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(source));

    QRCodeReader reader = new QRCodeReader();
    var result = reader.decode(binaryBitmap);
}

致电

var result = reader.decode(binaryBitmap);

始终返回null。

编辑:

似乎问题在于相机。它不专注于QR码,图像模糊,ZXing库无法解码。如何使相机对焦?

1 个答案:

答案 0 :(得分:0)

问题在于相机对焦。必须设置对焦模式。这是一个代码:

var parameters = _camera.GetParameters();
parameters.FocusMode = GetOptimalFocusMode(parameters);
_camera.SetParameters(parameters);

private String GetOptimalFocusMode(Android.Hardware.Camera.Parameters parameters)
{
    String result;
    IList<String> focusModes = parameters.SupportedFocusModes;

    if (focusModes.Contains(Android.Hardware.Camera.Parameters.FocusModeContinuousVideo))
    {
        result = Android.Hardware.Camera.Parameters.FocusModeContinuousVideo;
    }
    else if (focusModes.Contains(Android.Hardware.Camera.Parameters.FocusModeAuto))
    {
        result = Android.Hardware.Camera.Parameters.FocusModeAuto;
    }
    else
    {
        result = parameters.SupportedFocusModes.First();
    }

    return result;
}