安卓位图压缩方法是返回相同大小的图像,即使在不同的质量值



我正在尝试将图像文件缩放并压缩为PNG,相机图像格式为JPG,缩放成功,但仍未转换为PNG。其次,我认为compress方法针对不同的质量返回不同大小的byteArray,但即使在更改质量参数值时,我也会得到相同的大小。

这是我写的方法:

fun compressImage(file: File): File {
val outputBounds = 600
val scaleOptions = BitmapFactory.Options()
scaleOptions.inJustDecodeBounds = true
BitmapFactory.decodeFile(file.path, scaleOptions)
val scaleFactor =   if(scaleOptions.outHeight > outputBounds || scaleOptions.outWidth > outputBounds)
kotlin.math.max(scaleOptions.outWidth/outputBounds, scaleOptions.outHeight/outputBounds)
else 1
val outOptions = BitmapFactory.Options()
outOptions.inSampleSize = scaleFactor.roundToInt()
outOptions.inPreferredConfig = Config.RGB_565;
outOptions.inDither = true;
val decodedBMP = BitmapFactory.decodeFile(file.path, outOptions)
var byteOutStream = ByteArrayOutputStream()
val newFile = File(file.path)
val fileOutputStream = FileOutputStream(newFile, false)
var quality = 60
decodedBMP.compress(Bitmap.CompressFormat.PNG, quality, byteOutStream)
fileOutputStream.write(byteOutStream.toByteArray())
fileOutputStream.flush()
fileOutputStream.close()
return newFile
}

我在这里传递了一个文件作为参数,我正在用压缩图像覆盖该文件。

更新

我尝试使用Bitmap.CompressFormat.JPEG作为位图压缩配置,即压缩图像大小,但质量明显下降(我的意思是图片看起来像像素化的(,我读到Bitmap.CompressFormat.PNG给了你无损压缩,但它不起作用。

在Android开发者参考文档中,它说:

JPEGAPI 1级新增public static最终位图。压缩格式JPEG压缩为JPEG格式质量为0意味着对最小大小进行压缩100表示压缩以获得最高视觉质量

PNGAPI 1级新增public static最终位图。压缩格式PNG压缩为PNG格式。PNG是无损的,因此忽略质量

答案是这样的。由于忽略了质量,因此压缩为格式。PNG是无损的,这意味着它不会压缩。

最新更新