如何使用Zxing Library生成二维码?

时间:2017-01-12 06:24:00

标签: android qr-code zxing

我正在尝试为我的应用生成Qr代码。用户将输入一些文本,数据将被传递给下一个将显示QR码的活动。

这是我的代码。

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;
}
}

问题是当我按下按钮并转到下一个屏幕时,只出现白色屏幕,图像视图中也没有QR码。可能是什么错误?

4 个答案:

答案 0 :(得分:2)

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;
}

答案 1 :(得分:1)

 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;
}

答案 2 :(得分:0)

你在onCreate()方法之前初始化,因为它们没有正确初始化,需要一些时间来初始化。所以将初始化部分放在onStart()方法中。

答案 3 :(得分:-1)

你必须在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'

}

在Activity

中全局声明Class
    //qr code scanner object
private IntentIntegrator qrScan;

将此行放在onCreate()方法中。

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

现在在Button

上调用此方法
@Override
public void onClick(View view) {
    //initiating the qr code scan
    qrScan.initiateScan();
}