OutOfMemory while setting image in ImageView

后端 未结 2 645
后悔当初
后悔当初 2021-01-22 01:42

I am setting help screens images at 4 different places in my app. The activity code is the following-

@Override
    protected void onCreate(Bundle savedInstanceS         


        
相关标签:
2条回答
  • 2021-01-22 01:47

    What are the pixel sizes of the images? As the images are stored in the java heap, they are not compressed. That means that each pixel of the bitmap can take up to 32 bits = 4 bytes in the heap. So with an image with the size of 1920 x 1080 (maybe you are also targeting large resolution tablets), that is:

    1920 x 1080 x 4 bytes = 8294400 bytes, 8.29 megabytes.
    

    Now that might be OK on a tablet, but on an old phone which might have a heap space of 64 Megabytes, you might easily run into OutOfMemoryExceptions.

    So what can you do?

    1. If you are targeting phones only, you can resize the images to smaller sizes maybe? This is mainly based on trial and error, also depends on the usage of the image (blurred background image VS an image of a map with important details).

    2. Use a different bitmap config. The default is RGB_8888, which is 8 bits for each channel (ARGB) = 32 bits. If you don't need the alpha channel (transparency), and the image does not have to be super high quality, you should give RGB_565 a try. It has a very small quality decrease, but it's almost unnoticeable. In return it consumes halve the memory (5 + 6 + 5 = 16 bits per pixel).

    3. The most important fix: You can supply different images for different screen densities. So here's an example. Let's say we want to use the FullHD picture from the calculation. For smaller screens we scale it down, saving on memory. There are tools for scaling images down for the different densities, see this question. Following the density guidelines, you could put the following images with the sizes in the given directories:

      • drawable-xxhdpi: 1920x1080
      • drawable-xhdpi: 1280x720
      • drawable-hdpi: 960x540
      • drawable-mdpi: 640x360

      So while the image would take up 8.29 Mb heap space on a large tablet, it would only take up 921 Kb on an older phone, exactly what we wanted. It does come with the cost of increased APK size though, because now it contains 4 images instead of one.

    0 讨论(0)
  • 2021-01-22 01:51

    I think your problem described well here

    or you can change dimension of your image by photoshop to 50x50 etc.

    0 讨论(0)
提交回复
热议问题