Sergey Zabelnikov
Sergey Zabelnikov

Reputation: 1955

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

Upvotes: 1

Views: 819

Answers (2)

Pierangelo Orizio
Pierangelo Orizio

Reputation: 824

Try to set this to 100:

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

Upvotes: 1

Domain
Domain

Reputation: 11808

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

in this line of code here replace the 80 with 100 this indicates the compression. Thus your image will be compressed to 80% quality.

Though some quality loss is expected.

You could also try to save it to a .png instead of jpg and try if it helps

Upvotes: 2

Related Questions