使用Zxing生成二维码,以及保存到sdcard,图片变黑的问题

来源:互联网 发布:linux 下载速度 编辑:程序博客网 时间:2024/05/10 08:44

在app中,经常有生成识别二维码的功能,我们一般是使用zxing这个开源库来实现。

使用zxing生成Bitmap的代码如下:

/** * 生成二维码图片 * @param text 二维码文本 * @return */public static Bitmap createQrBitmap(String text,int qrWidth,int qrHeight) {        try {            // 需要引入core包            if (text == null || "".equals(text) || text.length() < 1) {                return null;            }            Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");            BitMatrix bitMatrix = new QRCodeWriter().encode(text,                    BarcodeFormat.QR_CODE, qrWidth, qrHeight, hints);                        int width = bitMatrix.getWidth();              int height = bitMatrix.getHeight();              int[] pixels = new int[width * height];                         for (int y = 0; y < height; y++) {                  for (int x = 0; x < width; x++) {                      if (bitMatrix.get(x, y)) {                          pixels[y * width + x] = 0xff000000;                      }else{                    pixels[y * width + x] = 0xffffffff;                     }                }              }                        Bitmap bitmap = Bitmap.createBitmap(width, height,                    Bitmap.Config.ARGB_8888);            bitmap.setPixels(pixels, 0, width, 0, 0, width, height);            return bitmap;        } catch (WriterException e) {            e.printStackTrace();        }return null;    }}
这样就可以生成一个二维码的图片,我们可以用一个ImageView来显示。

但是有很多人在保存的时候,打开发现时黑的。原因就是

for (int y = 0; y < height; y++) {  
                for (int x = 0; x < width; x++) {  
                    if (bitMatrix.get(x, y)) {  
                        pixels[y * width + x] = 0xff000000;  
                    }else{
                    pixels[y * width + x] = 0xffffffff; 
                    }
                }  
 }
这儿红色的代码没有加上去,加上就好了

0 0
原创粉丝点击