简体   繁体   中英

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: 之前 After: 后

As you can see, image became more sharpen

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

尝试将其设置为100:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM