save Bitmap to External Storage - Android Graphics

Android examples for Graphics:Bitmap Save

Description

save Bitmap to External Storage

Demo Code


//package com.java2s;
import android.content.Context;
import android.content.Intent;

import android.graphics.Bitmap;

import android.net.Uri;
import android.os.Environment;

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

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 w w .j  a  v a2 s .co  m
        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