2011-05-26 100 views
0

我必须在由相机捕获的图像上画一些东西。这适用于许多设备,但有时RAM太小或图片太大,并且该功能会因OutOfMemory异常而崩溃。新位图上的OutofMemory异常()

我怎么能: 一)优化代码,以防止这种异常 二)处理这个异常(从而使照片更小,可用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, 0) 
from_bmp.Dispose() 
'here I draw somethin in the Bitmap 
bmp.Save(deststring, System.Drawing.Imaging.ImageFormat.Jpeg) 
gr.Dispose() 
bmp.Dispose() 
+0

升级系统内存是最好的选择 – Predator 2011-05-26 15:08:39

+0

@Gens这种异常通常出现在很多平台上,不仅仅是Windows,而不仅仅是.NET。 – 2011-05-26 15:13:53

+0

这是net.cf,代码在移动设备上运行,我无法升级它们的Memorya^^ – 2red13 2011-05-26 15:14:21

回答

2

我可能会在您的位图上使用“使用”模式,并且请注意,通过简单再次尝试就可以解决创建位图时的OOM问题(here's a diatribe至于为什么)。我敢打赌,GC堆太满了并且第二次请求,特别是在收集之后,将成功。

我会仔细检查剩下的代码(未显示),并确保所有其他图形对象都正确放置 - CF不会自动清理图形对象的本机资源并且经常需要一些帮助(再次参见上面的链接)。

+0

是的,我应该提到,我执行一个GC.collect(),我处理每个Bitmaps我使用和在catch块我GC.WaitForPendingFinalizers后再次尝试 – 2red13 2011-05-26 15:17:55