Android How to - Save Bitmap to a file








Question

We would like to know how to save Bitmap to a file.

Answer

/*from  www.  j  ava 2  s. c  om*/
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

import android.graphics.Bitmap;
import android.os.Environment;
import android.util.Log;

public class Main {
  public static File saveBitmap(final Bitmap bitmap,
      final String subfolderInPictures, final String filename) {
    String extStorageDirectory = Environment.getExternalStorageDirectory()
        .toString();
    extStorageDirectory += File.separator + "Pictures" + File.separator
        + subfolderInPictures + File.separator;
    OutputStream outStream = null;

    final File out = new File(extStorageDirectory);
    out.mkdirs();
    Log.i("GEITH", "Writing Bitmap to " + extStorageDirectory + filename);
    final File file = new File(extStorageDirectory, filename);
    try {
      outStream = new FileOutputStream(file);
      bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
      outStream.flush();
      outStream.close();
    } catch (final Exception e) {
    }
    return file;
  }
}