views:

110

answers:

1

I am using a SqlDataReader and I am trying to read from a table I converted from an Access file, and is in SQL Server 2008.

The datatype is now a varbinary(max).

How do I convert this, so I can have it as System.Drawing.Image?

It is a Windows MetaFile and I want to convert it to a PNG or GIF and save it to the filesystem.

It appears this won't be correct as I get an error that it can't convert to Image.

System.Drawing.Image LocationImage = sdr.GetSqlBinary(2)

Thank you.

+1  A: 

Use SqlBytes. Use Image.FromStream to load the image from the SqlBytes.Stream. Use CommandBehavior.SequentialAccess on the reader to load large size images:

using (SqlDataReader sdr=cmd.ExecuteReader(CommandBehavior.SequentialAccess))
{
...
System.Data.SqlTypes.SqlBytes imageBytes = srd.GetSqBytes(2);
System.Drawing.Image locationImage = Image.FromStream(imageBytes.Stream);
}

To save it as PNG/GIF:

SqlCommand cmd = new SqlCommand("update table set image=@image where ...")

MemoryStream streamOutput = new MemoryStream();
image.Save(streamOutput, ImageFormat.Png);
SqlBytes imageBytes = new SqlBytes(streamOutput); 
cmd.Parameters.AddWithValue("@image", imageBytes);
cmd.ExecuteNonQuery()

Update

I'm not sure Image.FromStream can load WMF format. It can load EMF afaik, but I'm not sure about WMF. Perhaps routing the call through a Metafile(Stream) constructor will work, I'm not a graphics expert by any stretch.

Remus Rusanu
thank you. I am down to Image.FromStream, and you are correct that that didn't work, but using Metafile(Stream) doesn't as this constructor wants a byte array. So, I am working on that.
James Black