Android 位图解码和缩放质量损失
Android Bitmap Decode and Scale quality loss
我在 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;
}
但是我们在它之后的位图上有质量损失。我们能做些什么来解决这个问题?
之前:
后:
如您所见,图像变得更加清晰
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, fileOutputStream);
在这行代码中,将 80 替换为 100,这表示压缩。
因此您的图像将被压缩到 80% 的质量。
虽然预计会有一些质量损失。
您也可以尝试将其保存为 .png 而不是 jpg 并尝试是否有帮助
尝试将其设置为 100:
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
我在 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;
}
但是我们在它之后的位图上有质量损失。我们能做些什么来解决这个问题?
之前:
如您所见,图像变得更加清晰
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, fileOutputStream);
在这行代码中,将 80 替换为 100,这表示压缩。 因此您的图像将被压缩到 80% 的质量。
虽然预计会有一些质量损失。
您也可以尝试将其保存为 .png 而不是 jpg 并尝试是否有帮助
尝试将其设置为 100:
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);