生成二维码并将Bitmap保存成图片 您所在的位置:网站首页 葫芦娃邀请码二维码 生成二维码并将Bitmap保存成图片

生成二维码并将Bitmap保存成图片

2024-05-24 13:21| 来源: 网络整理| 查看: 265

本来项目集成的Zxing

Bitmap qrCode = EncodingHandler.createQRCode(shareUrl, DimenUtils.dp2px(105));

虽然这个类生成的Bitmap在ImageView上显示无误但是在保存成图片的时候却是一片黑色 找到原因是因为因为,有很多看图软件的背景是黑色的,当png透明时,当然也是黑色的,但是,换到ps里,或者其他看图软件中,就看出透明了。(这个答案是在论坛找到的http://bbs.csdn.net/topics/390835396) 生成二维码的方法:

public static Bitmap createQRCode(String str,int widthAndHeight) throws WriterException { Hashtable hints = new Hashtable(); hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); BitMatrix matrix = new MultiFormatWriter().encode(str, BarcodeFormat.QR_CODE, widthAndHeight, widthAndHeight); int width = matrix.getWidth(); int height = matrix.getHeight(); int[] pixels = new int[width * height]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { if (matrix.get(x, y)) { pixels[y * width + x] = BLACK; }else{ pixels[y * width + x] = WHITE; } } } Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565); bitmap.setPixels(pixels, 0, width, 0, 0, width, height); return bitmap; }

没想到的是google内部是集成了Zxing 这个库的,直接使用MultiFormatWriter生成二维码就行

将生成的二维码以图片的形式保存到本地图库

/** * 将bitmap保存到相册 */ public static void saveImageToGallery(Context context, Bitmap bmp) { // 首先保存图片 File appDir = new File(Environment.getExternalStorageDirectory(), "HuangjinBo"); if (!appDir.exists()) { appDir.mkdir(); } String fileName = System.currentTimeMillis() + ".jpg"; File file = new File(appDir, fileName); if (file.exists()) { file.delete(); } try { FileOutputStream fos = new FileOutputStream(file); bmp.compress(Bitmap.CompressFormat.JPEG, 0, fos); fos.flush(); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // 其次把文件插入到系统图库 try { MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null); Toast.makeText(context, "保存图片成功"+file.getAbsolutePath(), Toast.LENGTH_SHORT).show(); } catch (FileNotFoundException e) { e.printStackTrace(); } // 最后通知图库更新 Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); Uri uri = Uri.fromFile(file);intent.setData(uri); context. sendBroadcast(intent); }


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有