5

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.

Edward Falk
  • 9,991
  • 11
  • 77
  • 112
Bhavin Mistry
  • 185
  • 1
  • 4
  • 13
  • 1
    have you added uses permission to write external storage in manifest file. – ilango j Oct 21 '11 at 04:06
  • That would probably generate an exception, but good call. OP, are there any useful messages in the logcat output at all? – Edward Falk Jun 13 '13 at 22:36
  • BTW, minor style nit: those leading '_' in the variable names don't add anything to readability. I know they're used in other languages sometimes, but I wouldn't use them in Java. – Edward Falk Jun 13 '13 at 22:39

3 Answers3

5

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

Community
  • 1
  • 1
RajaReddy PolamReddy
  • 22,428
  • 19
  • 115
  • 166
  • Still it has the same problem, – Bhavin Mistry Oct 21 '11 at 04:10
  • When I run app from eclipse it works nice, but when I disconnect wire from my computer and loads the app from my phone, it doeesn't work properly. – Bhavin Mistry Oct 21 '11 at 04:12
  • @Bhavin Mistry Did it shows any error in log trace? if so please post it. – deepa Oct 21 '11 at 04:15
  • Also, what does String state = Environment.getExternalStorageState(); equal to? What is the value of Environment.MEDIA_MOUNTED.equals(state) – aleph_null Oct 21 '11 at 04:30
  • String state = Environment.getExternalStorageState() - always shows the state as mounted. And condition for Environment.MEDIA_MOUNTED.equals(state) always remains true. – Bhavin Mistry Oct 21 '11 at 05:04
  • @Deepa, I tried tracing files using Debug.startMethodTracing("newtest"); IMAGE.compress(Bitmap.CompressFormat.JPEG, 100, _fos); Debug.stopMethodTracing(); - While phone is connected and while not connected. Both files have some difference but I am not able to judge or understand them. Otherwise it doesn't shows any errors. – Bhavin Mistry Oct 21 '11 at 05:17
  • I noticed other thing, If I restart my phone, all images are loaded in gallary. – Bhavin Mistry Oct 21 '11 at 05:45
  • I tried something like this just after saving file, and its working good now ---- MediaStore.Images.Media.insertImage(getContentResolver(), _picFile.getAbsolutePath, _picFile.getName(), "Test Description"); – Bhavin Mistry Oct 21 '11 at 06:01
3
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        //4
        File file = new File(Environment.getExternalStorageDirectory()+File.separator +        "image.jpg");
        try {
            file.createNewFile();
            FileOutputStream fo = new FileOutputStream(file);
            //5
            fo.write(bytes.toByteArray());
            fo.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
Deepika Lalra
  • 1,035
  • 1
  • 10
  • 24
1
**This Code Cover the Following Topics**

1. Save a bitmap Image on sdcard a jpeg
2. Create a folder on sdcard
3. Create every file Separate name
4. Every file save with date and time
5. Resize the image in very small size
6. Best thing image Quality fine not effected from Resizing


The following method is used to create an image file using the bitmap

public void createImageFromBitmap(Bitmap bmp) {

    FileOutputStream fileOutputStream = null;
    try {

        // create a File object for the parent directory
        File wallpaperDirectory = new File("/sdcard/Capture/");
        // have the object build the directory structure, if needed.
        wallpaperDirectory.mkdirs();

        //Capture is folder name and file name with date and time
        fileOutputStream = new FileOutputStream(String.format(
                "/sdcard/Capture/%d.jpg",
                System.currentTimeMillis()));

        // Here we Resize the Image ...
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 100,
                byteArrayOutputStream); // bm is the bitmap object
        byte[] bsResized = byteArrayOutputStream.toByteArray();


        fileOutputStream.write(bsResized);
        fileOutputStream.close();


    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
    }
}


   and add this in manifest

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
Rashid Ali
  • 561
  • 6
  • 14