Search code examples
javaandroidbitmapimage-quality

Storing Bitmap in SD card loosing the image quality


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...


Solution

  • 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.