1

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

Sergey Zabelnikov
  • 1,855
  • 1
  • 14
  • 24

2 Answers2

2
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

Domain
  • 11,562
  • 3
  • 23
  • 44
  • Already tried to set 100, strange, but with 100 we get more quality lost, than with 80 – Sergey Zabelnikov Jul 28 '15 at 05:52
  • 1
    You could refer to this to use a byte array output stream http://stackoverflow.com/questions/8417034/how-to-make-bitmap-compress-without-change-the-bitmap-size – Domain Jul 28 '15 at 06:12
1

Try to set this to 100:

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