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

1 篇文章 0 订阅
1 篇文章 0 订阅

在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
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值