HANSGIELEN
Programmer
When loading an image with Image.FromFile the picturebox control locks the file so you get an exception when you try to delete it.
After long research I found the following solution, does anybody know something more elegant?
If Not (myPic.Image Is Nothing) Then
'get rid of any former image
myPic.Image.Dispose()
myPic.Image = Nothing
End If
myPic.Image = GetPicture("C:\Test\Sample.JPG"
Function GetPicture(ByVal filename As String) As Image
Dim eMsg As String
Dim sStream As FileStream
Dim mStream As MemoryStream
Dim sReader As BinaryReader
Dim BytesRead() As Byte
Try
'open filestream
sStream = New FileStream(filename, FileMode.Open, FileAccess.Read)
'declare memory stream in correct size
mStream = New MemoryStream(sStream.Length)
'create binary reader for file stream
sReader = New BinaryReader(sStream)
'read filestream to bytearray
BytesRead = sReader.ReadBytes(sStream.Length)
'write bytearray to memory stream
mStream.Write(BytesRead, 0, sStream.Length)
'create an image from the memory stream
GetPicture = New Bitmap(mStream)
'Cleanup
sStream.Close()
mStream.Close()
sReader = Nothing
sStream = Nothing
mStream = Nothing
Catch ex As Exception
eMsg = "Error in GetPicture" + vbCrLf + vbCrLf
eMsg = eMsg + ex.ToString
MsgBox(eMsg, MsgBoxStyle.Exclamation)
End Try
End Function
After long research I found the following solution, does anybody know something more elegant?
If Not (myPic.Image Is Nothing) Then
'get rid of any former image
myPic.Image.Dispose()
myPic.Image = Nothing
End If
myPic.Image = GetPicture("C:\Test\Sample.JPG"
Function GetPicture(ByVal filename As String) As Image
Dim eMsg As String
Dim sStream As FileStream
Dim mStream As MemoryStream
Dim sReader As BinaryReader
Dim BytesRead() As Byte
Try
'open filestream
sStream = New FileStream(filename, FileMode.Open, FileAccess.Read)
'declare memory stream in correct size
mStream = New MemoryStream(sStream.Length)
'create binary reader for file stream
sReader = New BinaryReader(sStream)
'read filestream to bytearray
BytesRead = sReader.ReadBytes(sStream.Length)
'write bytearray to memory stream
mStream.Write(BytesRead, 0, sStream.Length)
'create an image from the memory stream
GetPicture = New Bitmap(mStream)
'Cleanup
sStream.Close()
mStream.Close()
sReader = Nothing
sStream = Nothing
mStream = Nothing
Catch ex As Exception
eMsg = "Error in GetPicture" + vbCrLf + vbCrLf
eMsg = eMsg + ex.ToString
MsgBox(eMsg, MsgBoxStyle.Exclamation)
End Try
End Function