How to cut generate time to generate QR Code using Zxing

android, qr-code

Solution

You are calling getResources().getColor() inside double loop - ie when your image size is 100*100 pixels this will be called 10000 times. Instead assign color values to some variables outside of the loops and use these variables inside loops.

int color_black = getResources().getColor(R.color.colorBlack);
int color_white = getResources().getColor(R.color.colorWhite);

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) ? color_black : color_white;
    }
}

EDIT: added code example

Problem

I'm creating an app with QR barcode. The barcode load correctly, but somehow it load bit slow, about 3-5 secs after i tap/click the menu. Can we make it faster? or is it normal the page load that long? other part loading only takes 1 sec or less. the app also offline, so no internet connection needed. here my code to generate the QR barcode: ``` ImageView imageViewBarcode = (ImageView)findViewById(R.id.imageViewBarcode); try { bitmap = TextToImageEncode(barcode_user); imageViewBarcode.setImageBitmap(bitmap); } catch (WriterException e) { e.printStackTrace(); } ``` Those code above is put inside onCreate. So when the page load, it generate the barcode. Here the function to create barcode ``` 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.colorBlack):getResources().getColor(R.color.colorWhite); } } Bitmap bitmap = Bitmap.createBitmap(bitMatrixWidth, bitMatrixHeight, Bitmap.Config.ARGB_4444); bitmap.setPixels(pixels, 0, 500, 0, 0, bitMatrixWidth, bitMatrixHeight); return bitmap; } ```

Original source