how to prevent the Image.FromFile() method to lock the file

前端 未结 5 514
庸人自扰
庸人自扰 2020-12-06 02:50

I am using following code to put JPG\'s into a DataGridView\'s Image cell.

If strFileName.ToLower.EndsWith(\".jpg\") Then
     Dim inImg As Imag         


        
5条回答
  •  隐瞒了意图╮
    2020-12-06 03:03

    After searching the internet for long time I found out I can use this code without any error.

      Private fsIMG As FileStream
    Private Function SafeImageFromFile(FilePath As String) As Image
        'Ref:  http://stackoverflow.com/questions/18250848/how-to-prevent-the-image-fromfile-method-to-lock-the-file
        Dim img As Bitmap = Nothing
        fsIMG = New FileStream(FilePath, FileMode.Open, FileAccess.Read)
        Using b As New Bitmap(fsIMG)
            img = New Bitmap(b.Width, b.Height, b.PixelFormat)
            Using g As Graphics = Graphics.FromImage(img)
                g.DrawImage(b, Point.Empty)
                g.Flush()
            End Using
        End Using
        fsIMG.Close()
        Return img
    End Function
    

提交回复
热议问题