保存图片到相册
项目中我们经常用到,将图片保存至手机相册,并通知相册及时刷新,展示图片。
只需将代码复制至图片工具类,直接使用即可;
/**
* 保存图片到图库
* @param context
* @param bmp
*/
public static void saveImageToGallery(Context context, Bitmap bmp) {
// 首先保存图片
File appDir = new File(Environment.getExternalStorageDirectory(),
"desheng");
if (!appDir.exists()) {
appDir.mkdir();
}
String fileName = System.currentTimeMillis() + ".jpg";
File file = new File(appDir, fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
MyToastUtils.showShortToast(context, "保存失败");
e.printStackTrace();
} catch (IOException e) {
MyToastUtils.showShortToast(context, "保存失败");
e.printStackTrace();
}
// 其次把文件插入到系统图库
try {
MediaStore.Images.Media.insertImage(context.getContentResolver(),
file.getAbsolutePath(), fileName, null);
MyToastUtils.showShortToast(context, "保存成功");
} catch (FileNotFoundException e) {
MyToastUtils.showShortToast(context, "保存失败");
e.printStackTrace();
}
// 最后通知图库更新
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
Uri.fromFile(new File(file.getPath()))));
}
代码比较简单,只需直接复制粘贴至项目,把相应的内容补齐。