OrE*_*lse 3 vb.net memory-leaks memory-management image image-processing
我使用以下代码将图像作为缩略图加载到FlowLayoutPanel控件.不幸的是我得到了OutOfMemory异常.
正如您已经猜到的那样,内存泄漏是在线上找到的
Pedit.Image = System.Drawing.Image.FromStream(fs)
Run Code Online (Sandbox Code Playgroud)
那我怎么能优化下面的代码呢?
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
Run Code Online (Sandbox Code Playgroud)
更新:加载大量图像时出现问题(3264x2448px为300dpi - 每个图像大约为3Mb)
Image.FromFile(与您相关的FromStream)文档说OutOfMemoryException如果文件不是有效的图像格式或者GDI +不支持像素格式,它将抛出.您是否可能尝试加载不受支持的图像类型?
此外,文档Image.FromStream说您必须在图像的生命周期内保持流打开,因此即使您的代码加载了图像,您可能会收到错误,因为您在图像仍处于活动状态时关闭了文件.请参阅http://msdn.microsoft.com/en-us/library/93z9ee4x.aspx.