OutOfMemoryException loading big image to Bitmap object with the Compact Framework

一笑奈何 提交于 2019-11-29 07:49:31

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.

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!