OutOfMemoryException loading big image to Bitmap object with the Compact Framework

前端 未结 2 1802
无人及你
无人及你 2020-12-18 09:14

I have a problem with a memory leak.

I have this code in a button_click :

Private Sub Button3_Click(ByVal sender As System.Object, ByVal         


        
相关标签:
2条回答
  • 2020-12-18 09:59

    Your leaking Gdi handles, wrap the stream and bitmap in Using clauses.

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
    
        using ms As New IO.MemoryStream
            using bm As New Bitmap("\Application Data\imgs\IMG22.jpg")
                bm.Save(ms, Drawing.Imaging.ImageFormat.Jpeg)
            end using
        end using
    
    End Sub
    
    0 讨论(0)
  • 2020-12-18 10:01

    I don't believe the problem is a memory leak. Instead, the problem is a lack of available memory.

    Even though the compressed image size is 200kb, when you load it as a bitmap it will be decompressed and stored in memory in native Bitmap format. Given a height and width of 1500px each, and assuming a bitmap format of 32bpp (the default when not specified), you're looking at 9MB of allocated memory

    1500 * 1500 * 4 = 9MB.

    Given the memory constraints present in the mobile device OS (32MB/process - space allocated by system dlls), you may well be in a memory crunch scenario. It's unknown to me of course what other memory is allocated by the application you are running this code in.

    Try the same code on the same device with a smaller image. You should see that it executes fine.

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