Android 長按照片儲存 工具類
阿新 • • 發佈:2019-05-24
public class ImgUtils {
public static void saveImageToGallery(Context context, Bitmap bmp) {
final String[] items = new String[] { "儲存圖片"};
//圖片轉成Bitmap陣列
final Bitmap[] bitmap = new Bitmap[1];
bitmap[0] = bmp;
// Glide.with(context).load(url).asBitmap().into(new SimpleTarget<Bitmap>() {
// @Override
// public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
// bitmap[0] = resource;
// }
// });
// 首先儲存圖片 建立資料夾
File appDir = new File(Environment.getExternalStorageDirectory(), "shy");
if (!appDir.exists()) {
appDir.mkdir();
}
//圖片檔名稱
String fileName = "shy_"+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 (Exception e) {
e.printStackTrace();
}
// 其次把檔案插入到系統圖庫
String path = file.getAbsolutePath();
try {
MediaStore.Images.Media.insertImage(context.getContentResolver(), path, fileName, null);
} 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);
new ToastUtils(context).showToast("儲存成功");
}
}