最近看程式時,發現使用PictureBox顯示圖片時,會有「System.Drawing.Image.FromFile <System.OutOfMemoryException> 記憶體不足。」的錯誤。Google一下,發現有人說別使用Image.FromFile,所以在此Log一下。
Assign給PictureBox.Image屬性方式有以下方式
方法1, 使用Image.FromFileMe.PictureBox1.Image = Image.FromFile("f:\img1.jpg")
方法2, 使用Image.FromStream
Dim fs As System.IO.FileStream = System.IO.File.OpenRead("f:\img1.jpg")
Me.PictureBox1.Image = Image.FromStream(fs)
fs.Close()
建議使用方法2,因為使用方法1,Assign完後,image檔還是會被Lock,而方法2則不會。
清PictureBox.Image屬性的方式有以下方式,
方法1,直接用PictureBox.ImageIf Not (Me.PictureBox1.Image Is Nothing) ThenPictureBox1.Image.Dispose()
PictureBox1.Image = NothingEnd If
方法2,透過System.Drawing.Bitmap
Dim oldImg As System.Drawing.Bitmap = PictureBox1.ImagePictureBox1.Image = Nothing
If IsNothing(oldImg) = False ThenoldImg.Dispose()
End If
在Assign Image到PictureBox.Image之前,要先把原Image Dispose掉哦! 不然memory會一直吃下去哦!
參考PictureBox Dispose Problem
GDI+ 中发生一般性错误 System.OutOfMemoryException: 内存不足
範例Download Example
本文探讨了在.NET框架下使用PictureBox控件显示图片时遇到的“System.Drawing.Image.FromFile”导致的内存不足问题,并提供了两种解决方案:使用Image.FromStream替代Image.FromFile,以及正确的释放PictureBox.Image属性的方法。
2220

被折叠的 条评论
为什么被折叠?



