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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With