How to generate QR code using Zxing Library?

别等时光非礼了梦想. 提交于 2019-12-08 09:00:45

问题


I am trying to generate Qr code for my App. The user will enter some text an the the data will be passed to next activity which will display the QR code.

Here is my code.

public class QRgenerator extends AppCompatActivity {

ImageView imageView;
String Qrcode;
public static final int WIDTH = 500;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_qrgenerator);

    getID();

    Intent intent = getIntent();
    Qrcode = intent.getStringExtra("Data");


    //creating thread to avoid ANR exception
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            //the message to be encoded in the qr code.


            try {
                synchronized (this) {
                    wait(5000);

                    //runonUIthread on the main thread
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Bitmap bitmap = null;

                                bitmap = encodeasBitmap(Qrcode);
                                imageView.setImageBitmap(bitmap);
                            } catch (WriterException e) {
                                e.printStackTrace();
                                ;
                            } //end of catch block
                        } //end of rum method
                    });
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });
    t.start();
}

//method that returns the bitmap image of the QRcode.
public void getID() {
    imageView = (ImageView) findViewById(R.id.imageView2);
}

public Bitmap encodeasBitmap(String str) throws WriterException {

    BitMatrix result;
    try {
        result = new MultiFormatWriter().encode(str, BarcodeFormat.QR_CODE, WIDTH, WIDTH, null);
    } catch (IllegalArgumentException e) {
        //unsupported format
        return null;
    }
    int h = result.getHeight();
    int w = result.getWidth();

    int[] pixels = new int[w * h];

    for (int i = 0; i < h; i++) {
        int offset = i * w;
        for (int j = 0; j < w; j++) {
            pixels[offset + j] = result.get(j, i)? R.color.black:R.color.white;
        }
    }
    Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
    bitmap.setPixels(pixels, 0, 500, 0, 0, w, h);
    return bitmap;
}
}

The problem is when i press the button and go to the next screen only white screen appears and there is nor QR code in the Image view. What could be the mistake?


回答1:


package com.hellofyc.qrcode;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.support.annotation.IntRange;
import android.support.annotation.NonNull;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.util.HashMap;
import java.util.Map;

public class QRCodeHelper {

private Bitmap mLogo;
private ErrorCorrectionLevel mErrorCorrectionLevel;
private int mMargin;
private String mContent;
private int mWidth = 400, mHeight = 400;

public static QRCodeHelper newInstance() {
    return new QRCodeHelper();
}

public QRCodeHelper setLogo(Bitmap logo) {
    mLogo = logo;
    return this;
}

public QRCodeHelper setErrorCorrectionLevel(ErrorCorrectionLevel level) {
    mErrorCorrectionLevel = level;
    return this;
}

public QRCodeHelper setContent(String content) {
    mContent = content;
    return this;
}

public QRCodeHelper setWidthAndHeight(@IntRange(from = 1) int width, @IntRange(from = 1) int height) {
    mWidth = width;
    mHeight = height;
    return this;
}

public QRCodeHelper setMargin(@IntRange(from = 0) int margin) {
    mMargin = margin;
    return this;
}

public Bitmap generate() {
    Map<EncodeHintType, Object> hintsMap = new HashMap<>();
    hintsMap.put(EncodeHintType.CHARACTER_SET, "utf-8");
    hintsMap.put(EncodeHintType.ERROR_CORRECTION, mErrorCorrectionLevel);
    hintsMap.put(EncodeHintType.MARGIN, mMargin);
    try {
        BitMatrix bitMatrix = new QRCodeWriter().encode(mContent, BarcodeFormat.QR_CODE, mWidth, mHeight, hintsMap);
        int[] pixels = new int[mWidth * mHeight];
        for (int i=0; i<mHeight; i++) {
            for (int j=0; j<mWidth; j++) {
                if (bitMatrix.get(j, i)) {
                    pixels[i * mWidth + j] = 0x00000000;
                } else {
                    pixels[i * mWidth + j] = 0xffffffff;
                }
            }
        }
        Bitmap bitmap = Bitmap.createBitmap(pixels, 0, mWidth, mWidth, mHeight, Bitmap.Config.RGB_565);
        Bitmap resultBitmap;
        if (mLogo != null) {
            resultBitmap = addLogo(bitmap, mLogo);
        } else {
            resultBitmap = bitmap;
        }
        return resultBitmap;
    } catch (WriterException e) {
        e.printStackTrace();
    }
    return null;
}

private boolean isInRect(int x, int y) {
    return ((x > mMargin * 8 && x < mWidth - mMargin * 8) && (y > mMargin * 8 && y < mHeight - mMargin * 8));
}

private Bitmap addLogo(@NonNull Bitmap qrCodeBitmap, @NonNull Bitmap logo) {
    int qrCodeWidth = qrCodeBitmap.getWidth();
    int qrCodeHeight = qrCodeBitmap.getHeight();
    int logoWidth = logo.getWidth();
    int logoHeight = logo.getHeight();

    Bitmap blankBitmap = Bitmap.createBitmap(qrCodeWidth, qrCodeHeight, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(blankBitmap);

//        Paint paint = new Paint();
//        paint.setAntiAlias(true);
//        paint.setColor(Color.WHITE);
//        RectF rect = new RectF(50, 50, 200, 200);
//        canvas.drawRoundRect(rect, logoWidth, logoHeight, paint);

    canvas.drawBitmap(qrCodeBitmap, 0, 0, null);
    canvas.save(Canvas.ALL_SAVE_FLAG);
    float scaleSize = 1.0f;
    while ((logoWidth / scaleSize) > (qrCodeWidth / 5) || (logoHeight / scaleSize) > (qrCodeHeight / 5)) {
        scaleSize *= 2;
    }
    float sx = 1.0f / scaleSize;
    canvas.scale(sx, sx, qrCodeWidth / 2, qrCodeHeight / 2);
    canvas.drawBitmap(logo, (qrCodeWidth - logoWidth) / 2, (qrCodeHeight - logoHeight) / 2, null);
    canvas.restore();
    return blankBitmap;
}



回答2:


 public static Bitmap generateQRBitmap(String content, Context context,int flag){
    Bitmap bitmap = null;
    int width=256,height=256;

    QRCodeWriter writer = new QRCodeWriter();
    try {
        BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, width, height);//256, 256
       /* int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();*/
        bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                //bitmap.setPixel(x, y, bitMatrix.get(x, y) ? Color.BLACK : Color.WHITE);//guest_pass_background_color
                bitmap.setPixel(x, y, bitMatrix.get(x, y) ? Color.BLACK : context.getResources().getColor(R.color.guest_pass_background_color));//Color.WHITE
            }
        }
    } catch (WriterException e) {
        e.printStackTrace();
    }
    return bitmap;
}



回答3:


You have initialize before onCreate() method because they not initialize properly its takes some time to initialize. so put your initialization part in onStart() method.




回答4:


You have to mention in gradle

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.0.1'
testCompile 'junit:junit:4.12'

//add this dependency
compile 'com.journeyapps:zxing-android-embedded:3.4.0'

}

declare Class in globally in Activity

    //qr code scanner object
private IntentIntegrator qrScan;

put this line in onCreate() method.

 //intializing scan object
    qrScan = new IntentIntegrator(this);

Now call this method where you want on Button

@Override
public void onClick(View view) {
    //initiating the qr code scan
    qrScan.initiateScan();
}


来源:https://stackoverflow.com/questions/41606384/how-to-generate-qr-code-using-zxing-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!