Hesam
Hesam

Reputation: 53600

Android, How to store image in internal storage?

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;
    } 

Upvotes: 2

Views: 8010

Answers (2)

Zelter Ady
Zelter Ady

Reputation: 6348

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.

Upvotes: 7

Tim
Tim

Reputation: 6712

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();

Upvotes: 0

Related Questions