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

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

    I encountered the same situation and used this code:

    ' Create memory stream from file
    Dim ms As New MemoryStream()
    ' Open image file
    Using fs As New FileStream(.FileName, FileMode.Open, FileAccess.Read)
        ' Save to memory stream
        fs.CopyTo(ms)
    End Using
    
    ' Create image from the file's copy in memory
    Dim img = Image.FromStream(ms)
    

    I didn't dispose the memory stream because it allows to save the image later using exactly the same encoding as the original file, using this code:

    img.Save(someOtherStream, img.RawFormat)
    

提交回复
热议问题