新Bitmap的内存不足异常

问题描述

| 我必须在相机捕获的图像上绘制一些东西。这适用于许多设备,但有时RAM太小或图片太大,并且函数因OutOfMemory异常而崩溃。 我该如何: a)优化代码以防止出现此异常 b)处理此异常(使图片变小,免费的Ram等。 这是代码
 Dim from_bmp As Bitmap
 Dim bmp As Bitmap

 from_bmp = New Bitmap(picname)
 \'I also tryed this with a function which is creating the Bitmap from Filestream
 \'I also tryed this with the OpenNETCF.Drawing.Imaging.IImage
 \'If the Original Pictiure is too big,the function will crash here.

 bmp = New Bitmap(from_bmp.Width,from_bmp.Height + stampheight)
 \'Now I Create a bitmap which is higher than the original,in order to write the stamp beneth the picture

 Dim font As New System.Drawing.Font(\"Arial\",30,FontStyle.Regular)
 gr = Graphics.FromImage(bmp)
 gr.DrawImage(from_bmp,0)
 from_bmp.dispose()
 \'here I draw somethin in the Bitmap
 bmp.Save(deststring,System.Drawing.Imaging.ImageFormat.Jpeg)
 gr.dispose()
 bmp.dispose()
    

解决方法

我可能会为您的位图使用\“使用\”模式。此外,请注意,通常只需重试即可解决有关位图创建的OOM(此处是为什么的病)。我敢打赌,GC堆太满了,第二个请求(尤其是在收集之后)将成功。 我将遍历其余代码(未显示),并确保所有其他图形对象都得到正确处理。CF无法很好地处理图形对象的本机资源,并且通常需要一些帮助(再次请参见上面的链接)。