Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store Bitmap image to SD Card in Android

I am facing some strange problem with my android code, I have an image in Bitmap variable and want to save that file to SD card. I code as follow,

Bitmap IMAGE // Loaded from internet servers.;
try {
    File _sdCard = Environment.getExternalStorageDirectory();
    File _picDir  = new File(_sdCard, "MyDirectory");
    _picDir.mkdirs();

    File _picFile = new File(_picDir,  "MyImage.jpg");
    FileOutputStream _fos = new FileOutputStream(_picFile);
    IMAGE.compress(Bitmap.CompressFormat.JPEG, 100, _fos);
    _fos.flush();
    _fos.close();
    Toast.makeText(this, "Image Downloaded", 7000).show();
} catch (Exception ex) {
    ex.printStackTrace();
    Toast.makeText(this, ex.getMessage(), 7000).show();
}

I am using Sony Experia Arc as my testing device, when the phone is connected to my computer, the code works nice, it stores image and also displays in gallery. But when I disconnect phone from my computer and test the app, it doesn't save picture and doesn't show any exception.

like image 773
Bhavin Mistry Avatar asked Oct 21 '11 03:10

Bhavin Mistry


1 Answers

use this function

 void saveImage() {

    String root = Environment.getExternalStorageDirectory().toString();
    File myDir = new File(root + "/saved_images");

    String fname = "Image.jpg";
    File file = new File (myDir, fname);
    if (file.exists ()) file.delete (); 
    try {
           FileOutputStream out = new FileOutputStream(file);
           myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
           out.flush();
           out.close();

    } catch (Exception e) {
           e.printStackTrace();
    }
}

Check this answer will give more details Android saving file to external storage

like image 175
RajaReddy PolamReddy Avatar answered Oct 03 '22 18:10

RajaReddy PolamReddy