如何使用Zxing库生成二维码? [英] How to generate QR code using Zxing Library?

查看:15

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

这是我的代码.

公共类 QRgenerator 扩展 AppCompatActivity {图像视图图像视图;字符串二维码;public static final int WIDTH = 500;@覆盖protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_qrgenerator);获取 ID();意图意图 = getIntent();Qrcode = intent.getStringExtra("数据");//创建线程以避免ANR异常线程 t = 新线程(新可运行(){@覆盖公共无效运行(){//要在二维码中编码的消息.尝试 {同步(这个){等待(5000);//在主线程上runonUIthreadrunOnUiThread(new Runnable() {@覆盖公共无效运行(){尝试 {位图 bitmap = null;位图 = encodeasBitmap(Qrcode);imageView.setImageBitmap(位图);} catch (WriterException e) {e.printStackTrace();;}//catch块结束}//朗姆酒方法结束});}} catch (InterruptedException e) {e.printStackTrace();}}});t.start();}//返回二维码位图图像的方法.公共无效getID(){imageView = (ImageView) findViewById(R.id.imageView2);}公共位图 encodeasBitmap(String str) 抛出 WriterException {位矩阵结果;尝试 {result = new MultiFormatWriter().encode(str, BarcodeFormat.QR_CODE, WIDTH, WIDTH, null);} catch (IllegalArgumentException e) {//不支持的格式返回空;}int h = result.getHeight();int w = result.getWidth();int[] 像素 = 新的 int[w * h];for (int i = 0; i < h; i++) {int offset = i * w;for (int j = 0; j 

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

解决方案
package com.hellofyc.qrcode;导入 android.graphics.Bitmap;导入 android.graphics.Canvas;导入 android.support.annotation.IntRange;导入 android.support.annotation.NonNull;导入 com.google.zxing.BarcodeFormat;导入 com.google.zxing.EncodeHintType;导入 com.google.zxing.WriterException;导入 com.google.zxing.common.BitMatrix;导入 com.google.zxing.qrcode.QRCodeWriter;导入 com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;导入 java.util.HashMap;导入 java.util.Map;公共类 QRCodeHelper {私有位图mLogo;私人 ErrorCorrectionLevel mErrorCorrectionLevel;私人 int mMargin;私有字符串 mContent;私有 int mWidth = 400,mHeight = 400;公共静态 QRCodeHelper newInstance() {返回新的 QRCodeHelper();}public QRCodeHelper setLogo(位图标志){mLogo = 标志;返回这个;}公共 QRCodeHelper setErrorCorrectionLevel(ErrorCorrectionLevel level) {mErrorCorrectionLevel = 级别;返回这个;}公共 QRCodeHelper setContent(String content) {mContent = 内容;返回这个;}public QRCodeHelper setWidthAndHeight(@IntRange(from = 1) int width, @IntRange(from = 1) int height) {mWidth = 宽度;mHeight = 高度;返回这个;}public QRCodeHelper setMargin(@IntRange(from = 0) int margin) {mMargin = 保证金;返回这个;}公共位图生成(){Map提示映射 = 新的 HashMap<>();hintsMap.put(EncodeHintType.CHARACTER_SET, "utf-8");hintsMap.put(EncodeHintType.ERROR_CORRECTION, mErrorCorrectionLevel);提示Map.put(EncodeHintType.MARGIN, mMargin);尝试 {BitMatrix bitMatrix = new QRCodeWriter().encode(mContent, BarcodeFormat.QR_CODE, mWidth, mHeight,hintsMap);int[] 像素 = 新的 int[mWidth * mHeight];for (int i=0; i (qrCodeWidth/5) || (logoHeight/scaleSize) > (qrCodeHeight/5)) {比例尺 *= 2;}浮动 sx = 1.0f/scaleSize;canvas.scale(sx, sx, qrCodeWidth/2, qrCodeHeight/2);canvas.drawBitmap(logo, (qrCodeWidth - logoWidth)/2, (qrCodeHeight - logoHeight)/2, null);canvas.restore();返回空白位图;}
  • 原文

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?

解决方案
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;
}