3

我通过以下代码将图像添加到 FlowLayoutPanel 控件

Dim WithEvents Pedit As DevExpress.XtraEditors.PictureEdit

Private Sub LoadImagesCommon(ByVal fi As FileInfo)
        Pedit = New DevExpress.XtraEditors.PictureEdit
        Pedit.Width = 133
        Pedit.Height = 98
        Pedit.Image = Image.FromFile(fi.FullName)
        Pedit.Properties.SizeMode = DevExpress.XtraEditors.Controls.PictureSizeMode.Zoom
        Pedit.ToolTip = fi.Name
        AddHandler Pedit.MouseClick, AddressOf Pedit_MouseClick
        AddHandler Pedit.MouseEnter, AddressOf Pedit_MouseEnter
        AddHandler Pedit.MouseLeave, AddressOf Pedit_MouseLeave
        FlowLayoutPanel1.Controls.Add(Pedit)
    End Sub

问题是The process cannot access the file xxxx because it is being used by another process.当我尝试删除在上一步中加载的图像时出现以下错误。

                    FlowLayoutPanel1.Controls.Clear()
                    FlowLayoutPanel1.Refresh()
                    For Each fi As FileInfo In New DirectoryInfo(My.Settings.TempDirectory).GetFiles
                        RemoveHandler Pedit.MouseClick, AddressOf Pedit_MouseClick
                        RemoveHandler Pedit.MouseEnter, AddressOf Pedit_MouseEnter
                        RemoveHandler Pedit.MouseLeave, AddressOf Pedit_MouseLeave
                        File.Delete(fi.FullName)
                    Next

那么我在这里做错了什么?

4

3 回答 3

5

Image.FromFile实际上锁定了它加载的文件,并且只有在释放锁定后才释放锁定。

解决方案是将图像绘制到另一个图像的图形上下文中(从而有效地复制它)并处理原始图像。

于 2010-10-24T19:36:18.167 回答
5

啊哈!谢谢康拉德。

经过一番阅读,我也找到了另一种解决方法。

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() 

更新: 这是康拉德的建议。对于所有的新手,就像我一样:)

 Dim imgTemp As System.Drawing.Image  
 imgTemp = System.Drawing.Image.FromFile(strFilename, True)  
 Pedit.Image = New System.Drawing.Bitmap(imgTemp)  
 imgTemp.Dispose()  
 Pedit.Image.Save(strFilename)

这更好,因为 Image 对象在 FileStream 关​​闭后无法调用其 Save 方法。

于 2010-10-24T20:00:56.313 回答
0

I found this solution is the best to unlock the image file after it has been loaded to the PictureBox :

PictureBoxName.LOAD(image file name with full path)

于 2012-12-25T06:54:31.843 回答