Search code examples
androidbitmapbitmapfactory

Android Bitmap Decode and Scale quality loss


I need some help with BitmapFactory.decode and BitmapFactory.createScaledBitmap.

In our app we use this code for resize image:

 public static synchronized File resizeBitmap(File file, int expectedWidth) throws IOException {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inScaled = false;
    options.inDither = false;
    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
    Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);

    float width = bitmap.getWidth() / (float) expectedWidth;
    int expectedHeight = (int) (bitmap.getHeight() / width);

    Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, expectedWidth, expectedHeight, true);
    String path = Environment.getExternalStorageDirectory().toString();
    File tempFile = new File(path, "temp.jpg");
    if (tempFile.exists())
        tempFile.delete();

    FileOutputStream fileOutputStream = new FileOutputStream(tempFile.getAbsolutePath());
    scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, fileOutputStream);
    fileOutputStream.flush();
    fileOutputStream.close();
    return tempFile;
}

But we have quality loss on Bitmap after it. What we can do, to fix this problem?

Before: Before After: After

As you can see, image became more sharpen


Solution

  • Try to set this to 100:

    scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);