Java – Storing bitmaps on an SD card reduces image quality

Storing bitmaps on an SD card reduces image quality… here is a solution to the problem.

Storing bitmaps on an SD card reduces image quality

I’m storing bitmaps in an SD card while retrieving the quality that lost them. How do I fix this. Below is the code I store the bitmap in an 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();
        }
    }
}

Call this method:

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

Retrieve from SD card:

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

Thank you very much….

Solution

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

JPEG is a lossy compression format, and you have set the quality parameter to 0%. 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 where quality parameters don’t matter, such as PNG:

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 image as a file and the path in a database.

Related Problems and Solutions