Android:java.lang.OutOfMemoryError: Failed to allocate a 23970828 byte allocation with 2097152 free bytes and 2MB until OOM

前端 未结 30 2138
暗喜
暗喜 2020-11-21 07:33

I want to show the Bitmap image in ImageView from sd card which is stored already. After run my application is crash and getting Ou

30条回答
  •  不思量自难忘°
    2020-11-21 08:02

    I don't really recommend editing manifest like this

    android:hardwareAccelerated="false" , android:largeHeap="true"

    These options cause not smooth animation effect on your app. Moreover 'liveData' or changing your local DB(Sqlite, Room) activate slowly. It is bad for user experience.

    So I recommend RESIZE bitmap

    Below is the sample code

    fun resizeBitmap(source: Bitmap): Bitmap {
          val maxResolution = 1000    //edit 'maxResolution' to fit your need
          val width = source.width
          val height = source.height
          var newWidth = width
          var newHeight = height
          val rate: Float
    
                if (width > height) {
                    if (maxResolution < width) {
                        rate = maxResolution / width.toFloat()
                        newHeight = (height * rate).toInt()
                        newWidth = maxResolution
                    }
                } else {
                    if (maxResolution < height) {
                        rate = maxResolution / height.toFloat()
                        newWidth = (width * rate).toInt()
                        newHeight = maxResolution
                    }
                }
                return Bitmap.createScaledBitmap(source, newWidth, newHeight, true)
     }
    

提交回复
热议问题