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

前端 未结 5 511
庸人自扰
庸人自扰 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:13

    @ Chris: Opening approximately 100 large (3400x2200) images with your final code, I was receiving an invalid argument crash on [img = new bitmap(...], I have seen this before opening an image of zero size, but that was not the case here. I added fs.dispose and successfully opened thousands of images of the same size of the same set as the first test without issue. I'm interested in your comments on this.

    Private Function SafeImageFromFile(FilePath As String) As Image
        Dim img As Bitmap = Nothing
        Using fs As New FileStream(FilePath, FileMode.Open, FileAccess.Read)
            Using b As New Bitmap(fs)
                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
            fs.Dispose()
        End Using
        Return img
    End Function
    

提交回复
热议问题