【问题标题】:How to generate QR code using Zxing Library?如何使用 Zxing 库生成二维码?
【发布时间】:2017-01-12 17:01:46
【问题描述】:

我正在尝试为我的应用生成二维码。用户将输入一些文本,数据将被传递到下一个将显示 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;
}
}

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

【问题讨论】:

  • 除了return null之外还要记录异常吗?

标签: android qr-code zxing


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

    【讨论】:

    • 你能解释一下你在代码块之外做了什么吗?
    • java.lang.NullPointerException:尝试在代码 BitMatrix bitMatrix = new QRCodeWriter() 上的空对象引用上调用虚拟方法“java.lang.String java.lang.Object.toString()”。编码(mContent,BarcodeFormat.QR_CODE,mWidth,mHeight,hintsMap);
    【解决方案3】:

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

    【讨论】:

    • 你应该合并你的帖子
    【解决方案4】:

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

    现在在按钮上调用这个方法

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

    【讨论】:

    • 二维码不用于扫二维码。它用于生成代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多