Android 位图解码和缩放质量损失

标签 android bitmap bitmapfactory

我需要 BitmapFactory.decode 和 BitmapFactory.createScaledBitmap 方面的帮助。

在我们的应用程序中,我们使用此代码调整图像大小:

 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;
}

但是之后我们在 Bitmap 上有质量损失。我们能做些什么来解决这个问题?

之前: Before 后: After

如你所见,图像变得更加锐利

最佳答案

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

在这行代码中,将 80 替换为 100,这表示压缩。 因此,您的图像将被压缩到 80% 的质量。

虽然预计会有一些质量损失。

您也可以尝试将其保存为 .png 而不是 jpg 并尝试是否有帮助

关于Android 位图解码和缩放质量损失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31668015/

相关文章:

android - 优化使用 BitmapFactory.Options.inSampleSize 以提高速度

android - 更改位图的样本大小

android - 在 viewpager2 中禁用动画

Android-针对不同的屏幕尺寸调整图像

android - 在android中保存来自服务器的图像的最佳方法

wpf - 如何在 WPF 中拉伸(stretch)位图而不平滑像素

android - 如何调查在 Android 中使用 BitmapFactory 加载位图的问题? "getEntry failing because entryIndex..."

php - 移动应用开发中如何处理 "Semantic URL attacks"

android - 使用 Braintree Drop-In UI 集成 Google Pay

java - ANR 输入调度在 Android 4.4 上超时