基本上,我从用户存储中读取图像进行处理,在读取图像的同时,我计算inSampleSize以节省一些内存,以下是我的代码:
fun calculateInSampleSize(
options: BitmapFactory.Options,
reqWidth: Int,
reqHeight: Int
): Int {
// Raw height and width of image
val (height: Int, width: Int) = options.run { outHeight to outWidth }
var inSampleSize = 1
if (height > reqHeight || width > reqWidth) {
val halfHeight: Int = height / 2
val halfWidth: Int = width / 2
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while (halfHeight / inSampleSize >= reqHeight && halfWidth / inSampleSize >= reqWidth) {
inSampleSize *= 2
}
}
return inSampleSize
}
但是,我得到的是ArithmeticException:While循环条件中被零除:
halfHeight / inSampleSize >= reqHeight && halfWidth / inSampleSize >= reqWidth
个
我认为inSampleSize永远不会是零,因为它从1开始,并在每次迭代中乘以2.有人能帮帮我吗?这是怎么回事?
它只对一些用户崩溃(到目前为止有大约13次崩溃),我不能重现它.
编辑,添加了故障日志(log):
Non-fatal Exception: java.lang.ArithmeticException: divide by zero
at myapp.myapp.myapp.utils.UtilsKt.calculateInSampleSize(Utils.kt:108)
at myapp.myapp.myapp.utils.UtilsKt$resizeImageWithPixel$2.invokeSuspend(Utils.kt:464)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
at kotlinx.coroutines.internal.LimitedDispatcher.run(LimitedDispatcher.kt:42)
at kotlinx.coroutines.scheduling.TaskImpl.run(Tasks.kt:95)
at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.java:570)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:677)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:664)