save Bitmap to SD Storage - Android android.graphics

Android examples for android.graphics:Bitmap Load Save

Description

save Bitmap to SD Storage

Demo Code

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;

public class Main {

  public static boolean saveBitmap2SD(Bitmap bitmap, Context context, String filePath, String fileName) {
    String sdStatus = Environment.getExternalStorageState();
    if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // Check sd whether usable.
      return false;
    }/*from w  ww.  j a  v a 2 s. c om*/
    String name = new SimpleDateFormat().format(new Date()) + ".jpg";
    String filePath1 = "/sdcard/DCIM/Camera/";
    File file = new File(filePath1);
    if (!file.exists()) {
      if (!file.mkdirs())
        return false;
    }
    String fileName1 = filePath1 + name;
    FileOutputStream fos = null;
    try {
      fos = new FileOutputStream(fileName1);
      bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
      BufferedOutputStream bos = new BufferedOutputStream(fos);
      bos.flush();
      bos.close();
      fos.flush();
      // fos.write(data);
      fos.close();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        fos.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    // MediaStore.Images.Media.insertImage(context.getContentResolver(),bitmap,"","");
    context.sendBroadcast(
        new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
    return true;
  }

}

Related Tutorials