Android ZXing Get Barcode Image

HT03 picture HT03 · Jul 28, 2012 · Viewed 20.3k times · Source

I am using Zxing library to generate a barcode in my Android application

Intent intent = new Intent("com.google.zxing.client.android.ENCODE");

intent.putExtra("ENCODE_FORMAT", "UPC_A");
intent.putExtra("ENCODE_DATA", "55555555555");

startActivityForResult(intent,0);

Is there anyway to save the generated image in my application which is calling Zxing? I see that in my onActivityResult I get intent null.

Thanks in advance for your help

Answer

Girish Nair picture Girish Nair · Oct 19, 2012

Take the views cache and save it in bitmap something like this

View myBarCodeView = view.getRootView()
//Else this might return null
myBarCodeView.setDrawingCacheEnabled(true)
//Save it in bitmap
Bitmap mBitmap = myBarCodeView.getDrawingCache()

OR draw your own barcode or QR CODE

//Change the writers as per your need
private void generateQRCode(String data) {
    com.google.zxing.Writer writer = new QRCodeWriter();
    String finaldata =Uri.encode(data, "ISO-8859-1");
    try {
        BitMatrix bm = writer.encode(finaldata,BarcodeFormat.QR_CODE, 350, 350);
        mBitmap = Bitmap.createBitmap(350, 350, Config.ARGB_8888);
        for (int i = 0; i < 350; i++) {
            for (int j = 0; j < 350; j++) {
                mBitmap.setPixel(i, j, bm.get(i, j) ? Color.BLACK: Color.WHITE);
            }
        }
    } catch (WriterException e) {
        e.printStackTrace();
    }
    if (mBitmap != null) {
        mImageView.setImageBitmap(mBitmap);
    }
}
public void generateBarCode(String data){
    com.google.zxing.Writer c9 = new Code128Writer();
    try {
        BitMatrix bm = c9.encode(data,BarcodeFormat.CODE_128,350, 350);
        mBitmap = Bitmap.createBitmap(350, 350, Config.ARGB_8888);

        for (int i = 0; i < 350; i++) {
            for (int j = 0; j < 350; j++) {

                mBitmap.setPixel(i, j, bm.get(i, j) ? Color.BLACK : Color.WHITE);
            }
        }
    } catch (WriterException e) {
        e.printStackTrace();
    }
    if (mBitmap != null) {
        mImageView.setImageBitmap(mBitmap);
    }
}

Once you get the bitmap image just save it

//create a file to write bitmap data
    File f = new File(FilePath, FileName+".png");
    f.createNewFile();

    //Convert bitmap to byte array
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ImageBitmap.compress(CompressFormat.PNG, 0, bos);
    byte[] bytearray = bos.toByteArray();

    //Write bytes in file
    FileOutputStream fos = new FileOutputStream(f);
    fos.write(bytearray);
    fos.flush();
    fos.close();

You can also check a small library from github that i had created to create Barcode or QR Code

GZxingEncoder   Encoder = GZxingEncoder.getInstance();
Encoder.initalize(this);
//To generate bar code use this
Bitmap bitmap = Encoder.generateBarCode_general("some text")