[RESOLVED] showing images from db
I am using Access to store data and jpg images (I know, I know but that's what the boss wants at this time). And currently using VB6. What I need to do is retrieve the images from the db onto a user screen. Since it cannot be done in VB6 without writing it out to a file first and then loading the picture, I need to see if it is possible to do this in .net. What we want is simply to retrieve the record we want and display the stored image without having to do any writing out to disk. Is this possible?
Thanks in advance..
Re: showing images from db
An image field is just an array of bytes. You create a stream on that array and then create an image from the stream.
VB Code:
'Get the raw bytes from the field into an array.
Dim rawImageData As Byte() = DirectCast(myDataTable.Rows(0)("Image"), Byte())
'Create a stream on the byte array.
Dim imageStream As New IO.MemoryStream(rawImageData)
'Create an image object from the stream.
Dim picture As Image = Image.FromStream(imageStream)
Note that at this point it seems logical to close the stream, but due to the way GDI+ works that can cause issues in some situations. There are times when GDI+ refers back to the original stream to get information and, if it's closed, wil throw an exception. I learned this the hard way. I would suggest that you start by closing the stream and test thoroughly to see if any issues arise. If nothing does then great. If you start getting issues relating to that image or GDI+ in general then you will have to leave the stream open. The thing is, you have to be able to close the stream when you destroy the Iamage object, so that means that you have to keep a reference to the stream around. That's why it's a pain. You need a class-level variable for the stream instead of a local one, so that you can use it later on to close the stream. If you're using more than one image then it becomes even more of a pain, because you need an array or collection to store the stream references. In that case I'd recommend a Dictionary where the Images are the keys and the streams are the values. That way you can get the corresponding stream and close it whenever you destroy an Image.
Re: showing images from db
This is great!!
Although I am very (very) new to vb.net, this is the way to go. Thanks so much for all your input and links - really appreciate it.