Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Using ZXing Generate QR Code

People also ask

Can ZXing scan QR code?

On click of button_scan_qr_code , CaptureActivity will start scanning using default camera. Once it scans any QR code, it sends back the result to onActivityResult the MainActivity . ZXing also provides online QR Code Generator. Enter the required fields, generate and scan it to get the results.


Here is how you can generate an image with QR code from a string -

screenshot

First add the following line to build.gradle file in your Android Studio project:

dependencies {
    ....
    compile 'com.google.zxing:core:3.2.1'
}

Or if still using Eclipse with ADT-plugin add ZXing's core.jar from Maven repository to the libs subdir of your Eclipse ADT project (here fullscreen):

Eclipse

And then use the sample code from my MainActivity.java:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ImageView imageView = (ImageView) findViewById(R.id.qrCode);
    try {
        Bitmap bitmap = encodeAsBitmap(STR);
        imageView.setImageBitmap(bitmap);
    } catch (WriterException e) {
        e.printStackTrace();
    }
}

Bitmap encodeAsBitmap(String str) throws WriterException {
    BitMatrix result;
    try {
        result = new MultiFormatWriter().encode(str, 
            BarcodeFormat.QR_CODE, WIDTH, WIDTH, null);
    } catch (IllegalArgumentException iae) {
        // Unsupported format
        return null;
    }
    int w = result.getWidth();
    int h = result.getHeight();
    int[] pixels = new int[w * h];
    for (int y = 0; y < h; y++) {
        int offset = y * w;
        for (int x = 0; x < w; x++) {
            pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
        }
    }
    Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
    bitmap.setPixels(pixels, 0, width, 0, 0, w, h);
    return bitmap;
}

public static int white = 0xFFFFFFFF;
public static int black = 0xFF000000;
public final static int WIDTH = 500;


try
    {
        Bitmap bmp =  encodeAsBitmap("Life is a bitch");
        imgView.setImageBitmap(bmp);
    } catch (Exception e) {
        e.printStackTrace();
    }


Bitmap encodeAsBitmap(String str) throws WriterException {
    BitMatrix result;
    Bitmap bitmap=null;
    try
    {
        result = new MultiFormatWriter().encode(str,
                BarcodeFormat.QR_CODE, WIDTH, WIDTH, null);

        int w = result.getWidth();
        int h = result.getHeight();
        int[] pixels = new int[w * h];
        for (int y = 0; y < h; y++) {
            int offset = y * w;
            for (int x = 0; x < w; x++) {
                pixels[offset + x] = result.get(x, y) ? black:white;
            }
        }
        bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, WIDTH, 0, 0, w, h);
    } catch (Exception iae) {
        iae.printStackTrace();
        return null;
    }
    return bitmap;
}

ZXing library can provide easy way.

Origin is : Generate QRCode Android Example

add in dependencies

compile 'com.google.zxing:core:3.2.1'

Here is the method to conver string into QR Image

private Bitmap TextToImageEncode(String Value) throws WriterException {
        BitMatrix bitMatrix;
        try {
            bitMatrix = new MultiFormatWriter().encode(
                    Value,
                    BarcodeFormat.DATA_MATRIX.QR_CODE,
                    QRcodeWidth, QRcodeWidth, null
            );

        } catch (IllegalArgumentException Illegalargumentexception) {

            return null;
        }
        int bitMatrixWidth = bitMatrix.getWidth();

        int bitMatrixHeight = bitMatrix.getHeight();

        int[] pixels = new int[bitMatrixWidth * bitMatrixHeight];

        for (int y = 0; y < bitMatrixHeight; y++) {
            int offset = y * bitMatrixWidth;

            for (int x = 0; x < bitMatrixWidth; x++) {

                pixels[offset + x] = bitMatrix.get(x, y) ?
                        getResources().getColor(R.color.black):getResources().getColor(R.color.white);
            }
        }
        Bitmap bitmap = Bitmap.createBitmap(bitMatrixWidth, bitMatrixHeight, Bitmap.Config.ARGB_4444);

        bitmap.setPixels(pixels, 0, 500, 0, 0, bitMatrixWidth, bitMatrixHeight);
        return bitmap;
    }

Save geneated qr image

 public String saveImage(Bitmap myBitmap) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
        File wallpaperDirectory = new File(
                Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
        // have the object build the directory structure, if needed.

        if (!wallpaperDirectory.exists()) {
            Log.d("dirrrrrr", "" + wallpaperDirectory.mkdirs());
            wallpaperDirectory.mkdirs();
        }

        try {
            File f = new File(wallpaperDirectory, Calendar.getInstance()
                    .getTimeInMillis() + ".jpg");
            f.createNewFile();   //give read write permission
            FileOutputStream fo = new FileOutputStream(f);
            fo.write(bytes.toByteArray());
            MediaScannerConnection.scanFile(this,
                    new String[]{f.getPath()},
                    new String[]{"image/jpeg"}, null);
            fo.close();
            Log.d("TAG", "File Saved::--->" + f.getAbsolutePath());

            return f.getAbsolutePath();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return "";

    }

Following code worked for me:

...
String QRcode = "...";
new generateQrcode(qrcodeImageview).execute(QRcode);
...
private class generateQrcode extends AsyncTask<String, Void, Bitmap> {
        public final static int WIDTH = 400;
        ImageView bmImage;

        public generateQrcode(ImageView bmImage) {
            this.bmImage = bmImage;
        }

        protected Bitmap doInBackground(String... urls) {
            String Value = urls[0];
            com.google.zxing.Writer writer = new QRCodeWriter();
            Bitmap bitmap = null;
            BitMatrix bitMatrix = null;
            try {
                bitMatrix = writer.encode(Value, com.google.zxing.BarcodeFormat.QR_CODE, WIDTH, WIDTH,
                        ImmutableMap.of(EncodeHintType.MARGIN, 1));
                bitmap = Bitmap.createBitmap(400, 400, Bitmap.Config.ARGB_8888);
                for (int i = 0; i < 400; i++) {
                    for (int j = 0; j < 400; j++) {
                        bitmap.setPixel(i, j, bitMatrix.get(i, j) ? Color.BLACK
                                : Color.WHITE);
                    }
                }
            } catch (WriterException e) {
                e.printStackTrace();
            }
            return bitmap;
        }

        protected void onPostExecute(Bitmap result) {
            bmImage.setImageBitmap(result);
        }
    }