0

I'm trying to Change images formats, by using Bitmap compression, but decoding some images is generating OOM, so i came up with this:

    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)
        }
    }

Is it a good practice to wrap potential OOM with try/catch? or is there any other solution?

dali
  • 46
  • 1
  • 7
  • 1
    There is only one good reason to catch an OutOfMemoryError and that is to close down gracefully, cleanly releasing resources and logging the reason for the failure best you can (if it is still possible to do so). – Peter Kalef ' DidiSoft Jul 09 '19 at 06:52

1 Answers1

0

Outofmemoeryerror is not an exception. It is an error(Child of Throwable). In my opinion, it is not advisable to use try/ catch blocks to catch outofmemoryerror and recover from it. Even if try/catch blocks are used, Outofmemoeryerror will be triggered again and again when heap memory segment is exhausted. You can use the below two to avoid getting Outofmemoeryerrors

  1. Following best practices in code implementations
  2. Using proper memory settings using VM flags

For more details, you can check this site - https://outofmemoryerror.io/

Nirmal
  • 89
  • 6