System.Drawing.Image and jpg images

F

FlyFishGuy

I'm trying to perform a very simple operation of saving/reading an image
to/from SQL Server, but I must be missing something. There are a thousand
articles on the topic, but for some bizarre reason I can't find one relevant
to what I'm doing.

I take an uploaded jpg file, convert it to a byte array and save it in an
SQL image type field. This is pretty simple and no problem so far. I'd then
like to read the data and reconstruct the jpg. I read the data back into a
byte array, and this is where I'm stumped. I'd like to reconstruct the
original file as type System.Drawing.Image, but this is where my problem is.

If I take my byte array imageBytes(), and do this...

Dim objImage As System.Drawing.Image
Dim strm As New System.IO.MemoryStream

Try
strm.Read(imageBytes, 0, imageBytes.Length)
strm.Seek(0, IO.SeekOrigin.Begin)
objImage = System.Drawing.Image.FromStream(strm, False)

.... it throws an exception 'Parameter is not valid.' on the last line
(regardless of whether the last parm is True or False).

Now I don't really expect it to work, because there's no way for me to tell
the image object that it's a jpg. I assume it's expecting a bitmap. So
that's my problem. I obviously don't want to convert a compressed jpg to a
big bitmap before saving to the DB and I certainly don't want to stream the
bytes to a disk file and then read it back in, although both of these
workarounds should easily work.

So there's my problem. How can I read in a jpg, streamed as a byte array
into the DB, and then read/convert it into a System.Drawing.Image object.
I'm sure there must be a simple answer, it just seems to be escaping me.

Thanks for any help.
 
F

FlyFishGuy

OK. I've got it... duh!

Try
strm = New System.IO.MemoryStream(imageBytes)
objImage = System.Drawing.Image.FromStream(strm)

It's too easy in .NET to look for a complicated solution, when a simple one
exists.

Thank me for the response!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top