Android 使用 Zxing 生成二维码和条码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22371626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 05:53:12  来源:igfitidea点击:

Android Generate QR code and Barcode using Zxing

androidbarcodezxing

提问by Ciff

Code to generate Qr code using zxing is ---

使用zxing生成二维码的代码是---

It takes string data and the imageviewThis works just fine

它需要字符串数据,imageview这很好用

private void generateQRCode_general(String data, ImageView img)throws WriterException {
    com.google.zxing.Writer writer = new QRCodeWriter();
    String finaldata = Uri.encode(data, "utf-8");

    BitMatrix bm = writer.encode(finaldata, BarcodeFormat.QR_CODE,150, 150);
    Bitmap ImageBitmap = Bitmap.createBitmap(150, 150,Config.ARGB_8888);

    for (int i = 0; i < 150; i++) {//width
        for (int j = 0; j < 150; j++) {//height
            ImageBitmap.setPixel(i, j, bm.get(i, j) ? Color.BLACK: Color.WHITE);
        }
    }

    if (ImageBitmap != null) {
        qrcode.setImageBitmap(ImageBitmap);
    } else {
        Toast.makeText(getApplicationContext(), getResources().getString(R.string.userInputError),
                Toast.LENGTH_SHORT).show(); 
    }
}

Now my question is ,how to get bar codeusing the same library.i saw some files related to bar codesbut i am not sure how to do it. Since I want to generate the bar codewithin the application and not call any web service. Since i am already using zxing,no point in including itextand barbecue jars

现在我的问题是,如何bar code使用同一个库。我看到了一些相关的文件,bar codes但我不知道该怎么做。由于我想bar code在应用程序内生成 ,而不是调用任何web service. 因为我已经在使用 zxing,所以没有必要包含itext烧烤罐

采纳答案by Gaskoin

You are using QRCodeWriter. If you want to write another type of code, use another Writer.

您正在使用 QRCodeWriter。如果要编写其他类型的代码,请使用另一个 Writer。

Check this MultiFormatWriter- it can write any type of bar or find specific writers herein subfolders (this is from zxing library)

勾选此MultiFormatWriter-它可以写任何类型的酒吧或查找特定的作家在这里的子文件夹(这是从斑马线库)

回答by Ciff

Like Gaskoin told... MultiFormatWrite it worked :) here is the code.

就像Gaskoin 告诉... MultiFormatWrite 它工作:) 这里是代码。

      com.google.zxing. MultiFormatWriter writer =new  MultiFormatWriter();


        String finaldata = Uri.encode(data, "utf-8");

        BitMatrix bm = writer.encode(finaldata, BarcodeFormat.CODE_128,150, 150);
        Bitmap ImageBitmap = Bitmap.createBitmap(180, 40,Config.ARGB_8888);

        for (int i = 0; i < 180; i++) {//width
            for (int j = 0; j < 40; j++) {//height
                ImageBitmap.setPixel(i, j, bm.get(i, j) ? Color.BLACK: Color.WHITE);
            }
        }

        if (ImageBitmap != null) {
            qrcode.setImageBitmap(ImageBitmap);
        } else {
            Toast.makeText(getApplicationContext(), getResources().getString(R.string.userInputError),
                    Toast.LENGTH_SHORT).show(); 
        }

回答by Iván Martínez

I've tested the accepted answer to generate a Barcode but the output is blurrywhen used in a big ImageView. To get a high quality output, the widthof the BitMatrix, the Bitmap and the final ImageView should be the same. But doing so using the accepted answer will make the Barcode generation really slow (2-3 seconds). This happens because

我已经测试了可接受的答案以生成条形码,但是在大 ImageView 中使用时输出是模糊的。为了获得高质量的输出,BitMatrix、Bitmap 和最终 ImageView的宽度应该相同。但是使用已接受的答案这样做会使条码生成速度非常慢(2-3 秒)。发生这种情况是因为

Bitmap.setPixel()

is a slow operation, and the accepted answer is doing intensive use of that operation (2 nested for loops).

是一个缓慢的操作,接受的答案是大量使用该操作(2 个嵌套的 for 循环)。

To overcome this problem I've modified a little bit the Bitmap generation algorithm (only use it for Barcode generation) to make use of Bitmap.setPixels() which is much faster:

为了克服这个问题,我对位图生成算法(仅用于条码生成)进行了一些修改,以利用速度更快的 Bitmap.setPixels():

private Bitmap createBarcodeBitmap(String data, int width, int height) throws WriterException {
    MultiFormatWriter writer = new MultiFormatWriter();
    String finalData = Uri.encode(data);

    // Use 1 as the height of the matrix as this is a 1D Barcode.
    BitMatrix bm = writer.encode(finalData, BarcodeFormat.CODE_128, width, 1);
    int bmWidth = bm.getWidth();

    Bitmap imageBitmap = Bitmap.createBitmap(bmWidth, height, Config.ARGB_8888);

    for (int i = 0; i < bmWidth; i++) {
        // Paint columns of width 1
        int[] column = new int[height];
        Arrays.fill(column, bm.get(i, 0) ? Color.BLACK : Color.WHITE);
        imageBitmap.setPixels(column, 0, 1, i, 0, 1, height);
    }

    return imageBitmap;
}

This approach is really fast even for really big outputs and generates a high quality bitmap.

即使对于非常大的输出,这种方法也非常快,并生成高质量的位图

回答by Gaskoin

There you go,

你去,

public static Bitmap createBarCode (String codeData, BarcodeFormat barcodeFormat, int codeHeight, int codeWidth) {

    try {
        Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel> ();
        hintMap.put (EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);

        Writer codeWriter;
        if (barcodeFormat == BarcodeFormat.QR_CODE) {
            codeWriter = new QRCodeWriter ();
        } else if (barcodeFormat == BarcodeFormat.CODE_128) {
            codeWriter = new Code128Writer ();
        } else {
            throw new RuntimeException ("Format Not supported.");
        }

        BitMatrix byteMatrix = codeWriter.encode (
            codeData,
            barcodeFormat,
            codeWidth,
            codeHeight,
            hintMap
        );

        int width   = byteMatrix.getWidth ();
        int height  = byteMatrix.getHeight ();

        Bitmap imageBitmap = Bitmap.createBitmap (width, height, Config.ARGB_8888);

        for (int i = 0; i < width; i ++) {
            for (int j = 0; j < height; j ++) {
                imageBitmap.setPixel (i, j, byteMatrix.get (i, j) ? Color.BLACK: Color.WHITE);
            }
        }

        return imageBitmap;

    } catch (WriterException e) {
        e.printStackTrace ();
        return null;
    }
}

Of course you can support as many BarcodeFormats as you want, just change the constructor here :

当然,您可以根据需要支持任意数量的 BarcodeFormats,只需在此处更改构造函数:

Writer codeWriter;
if (barcodeFormat == BarcodeFormat.QR_CODE) {
    codeWriter = new QRCodeWriter ();
} else if (barcodeFormat == BarcodeFormat.CODE_128) {
    codeWriter = new Code128Writer ();
} else {
    throw new RuntimeException ("Format Not supported.");
}

回答by i.n.e.f

try this code

试试这个代码

Context context = getActivity();
Intent intent = new Intent("com.google.zxing.client.android.ENCODE");
intent.putExtra("ENCODE_TYPE", Text);
intent.putExtra("ENCODE_DATA", "12345678901");
intent.putExtra("ENCODE_FORMAT", "UPC_A");
startActivity(intent);

hope this helps you.

希望这对你有帮助。