Search code examples
c#sql-server-2008.net-3.5image-conversion

Read WMF image from SQL Server


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.


Solution

  • 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.