Android中把Bitmap图片保存到文件中

本文介绍了一种解决打印图片不生成的问题的方法。通过将图片保存到本地,并使用系统广播通知来确保图片能够被正确地生成和打印。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

做购彩APP时,打印彩票遇到了一些问题,因为打印的彩票是先生成图片再打印,所以想试试看直接打印资源文件中图片是否有问题。

因此需要先把生成的图片保存下来再放到资源文件中,生成png格式图片代码如下:

String dir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/goucaiapp/";

Bitmap bitmap = InitTextQRCodeUtil.getCustomImage(this);
img_test.setImageBitmap(bitmap);
File file = new File(dir + "printBitmap.png");
Log.v("info", "file.getAbsolutePath()===" + file.getAbsolutePath());
if (! file.exists()) {
try {
if (! file.createNewFile()) {
ToastUtil.showToast(getApplicationContext(), "文件创建失败");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
bos.flush();
bos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

在应用中执行上述代码后发现并没有生成相对应的png格式图片,但是也没有报错,没有任何提示信息,网上查了相关资料才知道还需要发送一个系统广播通知终端有图片更新:

Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri uri = Uri.fromFile(file);
intent.setData(uri);
sendBroadcast(intent);

这样执行完代码后才看到保存在文件中的png格式图片。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值