我正在尝试缩放图像文件,然后将其压缩为PNG,相机图像格式为JPG,并且已成功缩放,但仍未转换为PNG。其次,我认为compress
方法针对不同的质量返回不同的大小byteArray
,但是即使更改质量参数值,我也得到相同的大小。
这是我写的方法:
fun compressImage(file: File): File {
val outputBounds = 600
val scaleOptions = BitmapFactory.Options()
scaleOptions.inJustDecodeBounds = true
options.inPreferredConfig = Config.RGB_565;
options.inDither = 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()
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
}
我在这里传递了一个文件作为参数,我正在用压缩图像覆盖文件。
您必须使outOptions.inSampleSize等于2的幂。因此它可以是2、4、8、16…等等,不要四舍五入您的scaleFactor