2

I want to store bitmap image on internal storage (not external storage). I have written this code but it seems something has problem. Because when i download image from DDMS, I can't open it.

public String writeFileToInternalStorage(Context context, Bitmap outputImage) {

        String fileName = Long.toString(System.currentTimeMillis()) + ".png";

        try {
            OutputStreamWriter osw = new OutputStreamWriter(context.openFileOutput(fileName, Context.MODE_PRIVATE));
            osw.write(outputImage.toString());
            Log.i(TAG, "Image stored at: " + fileName);
        } catch (Exception e) {
            Log.w(TAG, e.toString()); 
            fileName = null;
        } 

        return fileName;
    } 
Hesam
  • 52,260
  • 74
  • 224
  • 365
  • You're attempting to write out your `Bitmap` as a `String`, using `outputImage.toString()`. I don't even know what that would get you, but not a valid image, I think. [Take a look at this](http://stackoverflow.com/questions/649154/android-bitmap-save-to-location) – Nate Jul 22 '12 at 10:45

2 Answers2

7

outputImage.toString() is not the image :) the contant you put on the file is not the binary data, but some string!

A way to do it is this:

public String writeFileToInternalStorage(Context context, Bitmap outputImage) {
    String fileName = Long.toString(System.currentTimeMillis()) + ".png";

    final FileOutputStream fos = openFileOutput(fileName, Context.MODE_PRIVATE);
    outputImage.compress(CompressFormat.PNG, 90, fos);
}

I coded directly into the browser, it is possible to have some syntax errors, but the code should work.

Zelter Ady
  • 6,266
  • 12
  • 48
  • 75
  • Thanks dear Zelter, But unfortunately when I use this code new red line comes below "openFileOutput" and I can't run the application. – Hesam Jul 22 '12 at 10:54
  • It says there is not a method in class and ask me to create it. – Hesam Jul 22 '12 at 10:55
  • call `context.openFileOutput` – Ron Jul 22 '12 at 11:07
  • Thanks dear Zelter, it works fine. Just, can you tell me how to get image address? because after saving image i should save its path to database for later reference. Thanks – Hesam Jul 22 '12 at 22:49
  • 2
    I found the way. :) String fileName = Long.toString(System.currentTimeMillis()) + ".png"; File cacheDir = context.getFilesDir(); String path = cacheDir.getPath() + fileName; – Hesam Jul 22 '12 at 22:59
0

The problem is that you use .toString() instead of compressing the Bitmap into a FileOutputStream:

FileOutputStream out = new FileOutputStream(filename);
outputImage.compress(Bitmap.CompressFormat.PNG, 90, out);

The internal storage can be retrieved via the Context, too.

File cacheDir = context.getCacheDir();
Tim
  • 6,692
  • 2
  • 25
  • 30
  • Thanks Tim, But it doesn't work as well. It throws "FileNotFoundException". Complete message from logcat is: java.io.FileNotFoundException: /1342996573233.png: open failed: EROFS (Read-only file system) – Hesam Jul 22 '12 at 22:40