我正在尝试通过使用位图压缩来更改图像格式,但是解码某些图像正在生成OOM,所以我想到了:
fun compressImage(filePath: String, sampleRate: Int? = null): Bitmap {
val options = BitmapFactory.Options().apply {
inJustDecodeBounds = true
}
BitmapFactory.decodeFile(filePath, options)
val reqSampleRate = sampleRate ?: calculateInSampleSize(options, maxWidth, maxHeight)
try {
options.inSampleSize = reqSampleRate
options.inPreferredConfig = Bitmap.Config.ARGB_8888
options.inJustDecodeBounds = false
return BitmapFactory.decodeFile(filePath, options)
} catch (e: OutOfMemoryError) {
System.gc()
// increase sample rate to get smaller bitmap size
return compressImage(filePath, reqSampleRate + 2)
}
}
将潜在的OOM与Try/Catch结合起来是一个好习惯吗?还是还有其他解决方案?
outofmoeryReror不例外。这是一个错误(可投掷的孩子(。我认为,不建议使用尝试/捕获块来捕获OutofmemoryError并从中恢复。即使使用了尝试/捕获块,OutofmoeryReror 当堆内存段耗尽时,将一次又一次触发。您可以使用以下两个以避免获得offmoeryRererrors
- 遵循代码实施中的最佳实践
- 使用VM标志使用正确的内存设置
有关更多详细信息,您可以检查此站点-https://outofmemoryerror.io/