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

来源:互联网 发布:php mysql 存储过程 编辑:程序博客网 时间:2024/05/16 08:12

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


原创粉丝点击