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格式图片。


Android 4.4及以上版本(API级别19),你可以使用`Bitmap.compress()`方法将Bitmap对象保存文件。以下是基本步骤: 1. 创建一个File对象,指定你要保存文件的位置和名称: ```java File outputImageFile = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "example.jpg"); ``` 这里假设你想在设备的图片库目录下创建一个名为"example.jpg"的新文件。`getExternalFilesDir(Environment.DIRECTORY_PICTURES)`获取外部存储的图片目录。 2. 使用合适的压缩格式(例如PNG、JPEG等)和质量(范围0-100,100表示最高质量但文件较大,0表示最小质量但文件更小)来压缩Bitmap: ```java Bitmap.CompressFormat format = Bitmap.CompressFormat.JPEG; // 或其他格式,比如Bitmap.CompressFormat.PNG int quality = 100; // 质量调整,范围0-100 try { FileOutputStream fos = new FileOutputStream(outputImageFile); bitmap.compress(format, quality, fos); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } ``` 这里使用了JPEG压缩格式,并设置了质量为100。如果需要更改压缩格式或质量,只需修改`format`和`quality`变量即可。 3. 最后别忘了关闭文件流以释放资源: 完整示例: ```java Bitmap bitmap = ... // 获取你的Bitmap对象 try { File outputImageFile = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "example.jpg"); FileOutputStream fos = new FileOutputStream(outputImageFile); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos); fos.close(); Log.i("SaveSuccess", "Bitmap saved successfully."); } catch (Exception e) { Log.e("SaveError", "Failed to save bitmap: ", e); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值