Storing Bitmap in SD card loosing the image quality

896 views Asked by At

I am storing the bitmap in SD card while retrieving loosing their quality. how can i resolved this issue. Below is my code to store the bitmap in Sd card.

public void saveExternalPrivateStorage(File folderDir, String fname,
        Bitmap bitmap) {

    File file = new File(folderDir, fname);

    if (file.exists()) {
        file.delete();
    }
    if ((folderDir.mkdirs() || folderDir.isDirectory())) {
        try {
            FileOutputStream out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 0, out);
            out.flush();
            out.close();
            System.out.println("Stored");
            System.out.println(file.getAbsolutePath());
            System.out.println("Stored");

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

invoking this method:

File folderDir= new File(getActivity().getExternalFilesDir("myfolder"),"/images");
storeImagesIndevices.saveExternalPrivateStorage(folderDir,filename,imgBitmapUrls.get(i));

Retrieving from SD card:

Bitmap bitmap2 = BitmapFactory.decodeFile(folderDir+"/"+data.getTid());
        dbimgBitmapUrls.put(data.get_tid()-1, bitmap2);

Thanks a lot...

2

There are 2 answers

2
laalto On BEST ANSWER
bitmap.compress(Bitmap.CompressFormat.JPEG, 0, out);

JPEG is a lossy compression format and you've setting 0% as the quality parameter. Something around 70% is usually a good compromise between file size and image quality:

bitmap.compress(Bitmap.CompressFormat.JPEG, 70, out);

Or use a lossless format such as PNG where the quality parameter does not matter:

bitmap.compress(Bitmap.CompressFormat.PNG, 0, out);

Can store the bitmap in SQLite? is it good approach. In my case number of images not that much

You can but you shouldn't. A better approach is to store the images as files and just store the path in database.

2
Stefano Sanfilippo On

You should use a higher compression quality:

 bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);

The second parameter to compress is a 0-100 number which marks the tradeoff between quality and file size:

  • 0 = smallest file size, worst quality
  • 100 = largest file size, best quality

Probably you will want an intermediate value, just play a bit until you find a satisfactory value for your application. Also refer to compress() javadoc.

If it is the case, you could also use a lossless format (like PNG) instead of JPEG.