使用照片中的xzing扫描代码

时间:2016-07-18 00:55:47

标签: android zxing

我有功能请求。当前流程是供用户扫描代码(不是QR码,不确定它是什么,zxing会扫描它),然后扫描测试卡。

客户要求我允许用户从库中导入测试。所以我们需要能够从图像中扫描代码。

是否可以在zxing中执行此操作或者我不能使用相机/功能?

谢谢!

1 个答案:

答案 0 :(得分:0)

这是我的解决方案。我不得不缩小图像尺寸,并将颜色与zxing一起使用。我可能会将转换添加到灰度,但今天不是..

 public static String scanDataMatrixImage(Bitmap bitmap) {
    bitmap = doInvert(bitmap);

    double scaling = getScaling(bitmap);
    Bitmap resized;
    if(scaling>0) {
         resized = Bitmap.createScaledBitmap(bitmap, (int) (bitmap.getWidth() * scaling), (int) (bitmap.getHeight() * scaling), true);
    }
    else{
         resized = bitmap;
    }

    String contents = null;

    int[] intArray = new int[resized.getWidth() * resized.getHeight()];
    //copy pixel data from the Bitmap into the 'intArray' array
    resized.getPixels(intArray, 0, resized.getWidth(), 0, 0, resized.getWidth(), resized.getHeight());

    LuminanceSource source = new RGBLuminanceSource(resized.getWidth(), resized.getHeight(), intArray);
    BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(source));


    MultiFormatReader reader = new MultiFormatReader();

    try

    {
        Result result = reader.decode(binaryBitmap);
        contents = result.getText();
    } catch (
            Exception e
            )

    {
        Log.e("QrTest", "Error decoding barcode", e);
    }

    return contents;
}


 private static double getScaling(Bitmap bitmap){
    int width = bitmap.getWidth();
    int height = bitmap.getHeight();
    int smallest = width;
    if(smallest > height){
        smallest = height;
    }
    double ratio = 200.0/smallest;
    return ratio;
}

public static Bitmap doInvert(Bitmap src) {
    // create new bitmap with the same settings as source bitmap
    Bitmap bmOut = Bitmap.createBitmap(src.getWidth(), src.getHeight(), src.getConfig());
    // color info
    int A, R, G, B;
    int pixelColor;
    // image size
    int height = src.getHeight();
    int width = src.getWidth();

    // scan through every pixel
    for (int y = 0; y < height; y++)
    {
        for (int x = 0; x < width; x++)
        {
            // get one pixel
            pixelColor = src.getPixel(x, y);
            // saving alpha channel
            A = Color.alpha(pixelColor);
            // inverting byte for each R/G/B channel
            R = 255 - Color.red(pixelColor);
            G = 255 - Color.green(pixelColor);
            B = 255 - Color.blue(pixelColor);
            // set newly-inverted pixel to output image
            bmOut.setPixel(x, y, Color.argb(A, R, G, B));
        }
    }

    // return final bitmap
    return bmOut;
}