I'm reading images from a database. I read the binary / blob for a field, and I convert it to an image like this:
Public Function BytesToImage(ByVal ByteArr() As Byte) As Image
If ByteArr.Length < 1 Then
Return Nothing
End If
Dim ImageStream As MemoryStream 'Needs to stay open for the image's life-time
Dim nImage As Image = Nothing
Try
ImageStream = New MemoryStream(ByteArr)
nImage = Image.FromStream(ImageStream, True)
Catch ex As Exception
nImage = Nothing
End Try
Return nImage
End Function
I can't use "Using nImageStream As New MemoryStream(ByteArr)" because the image goes "dead" after some time. According to the documentation, MemoryStream needs to stay open for the image's lifetime.
Now I would like to know what's actually the best. Should I not care about the MemoryStream and just accept that it's there and still open "in the background", or should I rather clone the image and close the memorystream?
According to JonSkeet in this question, you don't need to worry about keeping a reference around.
Since you've already got a Try/Catch in your code, boil it down to:
Public Function BytesToImage(ByVal ByteArr() As Byte) As Image
Try
Return Image.FromStream(New MemoryStream(ByteArr), True)
Catch ex As Exception
Return Nothing
End Try
End Function