LoginSignup
42
43

More than 5 years have passed since last update.

AndroidでBitmapの一時保存

Last updated at Posted at 2015-05-28

画像の一時保存の方法

画像処理するアプリを作成する場合、
カメラやギャラリーで取り込んだ元のデータを一時的にもっておきたい時があります。
そのときメンバー変数にBitmapをもっておくと、ある程度でかい画像をもっておくと
すぐにOutOfMemoryがおきてしまいます。

いままでに一時的にデータを保持する方法をいろいろ試したのでメモしておく。

メンバー変数

メリット

  • 簡単

デメリット

  • アクティビティ終了されたらきえる
  • メモリにやさしくない

コード

private Bitmap cache;

ファイルに書き出す

メリット

-メモリ優しい

デメリット

  • 残ってしまった時に、ギャラリーで表示されてしまう

コード

 try {
 // sdcardフォルダを指定
 File root = Environment.getExternalStorageDirectory();

 // 日付でファイル名を作成 
 Date mDate = new Date();
 SimpleDateFormat fileName = new SimpleDateFormat("yyyyMMdd_HHmmss");

 // 保存処理開始
 FileOutputStream fos = null;
 fos = new FileOutputStream(new File(root, fileName.format(mDate) + ".jpg"));

 // jpegで保存
 mBitmap.compress(CompressFormat.JPEG, 100, fos);

 // 保存処理終了
 fos.close();
 } catch (Exception e) {
 Log.e("Error", "" + e.toString());
 }

SharedPreferencesに書き出す

メリット

  • メモリにやさしい
  • ホームボタンやアクティビティ終了されても、変な途中成果物がギャラリーで表示されない

コード

書き出し

Bitmap bitmap = ... //保存したいBitmap
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
String bitmapStr = Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);

context.getSharedPreferences("hogehoge", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("key", bitmapStr);
editor.apply();

読み込み

context.getSharedPreferences("hogehoge", Context.MODE_PRIVATE);
SharedPreferences pref = createSharedPreferences(context);
String s = pref.getString("key", "");
if (!s.equals("")) {
  BitmapFactory.Options options = new BitmapFactory.Options();
  byte[] b = Base64.decode(s, Base64.DEFAULT);
  Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length).copy(Bitmap.Config.ARGB_8888, true);
}

まとめ

現状はSharedPreferencesで保存する方法が一番安定している。
もちろんアプリ管理からデータ削除されればきえるので、あくまでもキャッシュです。
それはファイルでもっているときも同じですので。。。

追記

@eneim さんより情報いただきました。
ありがとうございます。

まだ試してないのでなんともですが、
キャッシュに関していろいろあるみたいです。。
http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html

42
43
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
42
43