我使用以下代码将图像作为缩略图加载到 FlowLayoutPanel 控件。不幸的是我遇到了 OutOfMemory 异常。
正如您已经猜测的那样,内存泄漏是在该行发现的
Pedit.Image = System.Drawing.Image.FromStream(fs)
那么我该如何优化以下代码呢?
Private Sub LoadImagesCommon(ByVal FlowPanel As FlowLayoutPanel, ByVal fi As FileInfo)
Pedit = New DevExpress.XtraEditors.PictureEdit
Pedit.Width = txtIconsWidth.EditValue
Pedit.Height = Pedit.Width / (4 / 3)
Dim fs As System.IO.FileStream
fs = New System.IO.FileStream(fi.FullName, IO.FileMode.Open, IO.FileAccess.Read)
Pedit.Image = System.Drawing.Image.FromStream(fs)
fs.Close()
fs.Dispose()
Pedit.Properties.SizeMode = DevExpress.XtraEditors.Controls.PictureSizeMode.Zoom
If FlowPanel Is flowR Then
AddHandler Pedit.MouseClick, AddressOf Pedit_MouseClick
AddHandler Pedit.MouseEnter, AddressOf Pedit_MouseEnter
AddHandler Pedit.MouseLeave, AddressOf Pedit_MouseLeave
End If
FlowPanel.Controls.Add(Pedit)
End Sub
Update:加载大量图像时会出现此问题(3264x2448px,300dpi - 每个图像约为 3Mb)
文档用于Image.FromFile
(这与你的FromStream
)说它会抛出OutOfMemoryException
如果文件不是有效的图像格式或者 GDI+ 不支持像素格式。您是否可能尝试加载不受支持的图像类型?
另外,文档Image.FromStream
表示您必须在图像的生命周期内保持流打开,因此即使您的代码加载了图像,您也可能会收到错误,因为您在图像仍处于活动状态时关闭文件。看http://msdn.microsoft.com/en-us/library/93z9ee4x.aspx.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)