Cast WIA.Imagefile to System.Drawing.Image

Yesterday I made an interface to a flatbed scanner to scan in an image straight to your hard drive using C#. And of course, someone asked, why is there no Preview? As it turns out, straight casting a WIA image to a System.Drawing.Image is not possible. 

Found a workaround by getting the binary data of the WIA.Image and piping it through the memory stream into an image.
Like so:
 //this should create an image file in memory
                    img = (ImageFile)WiaCommonDialog.ShowTransfer(Item, "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}", false);
                    //process image:
                    //one would do image processing here
                    Byte[] imageBytes = (byte[])img.FileData.get_BinaryData(); // <– Converts the ImageFile to a byte array
                    MemoryStream ms = new MemoryStream(imageBytes);
                    Image image = Image.FromStream(ms);
                    pictureBox1.Image = image;
This snippet is inserted straight into my previous post ( http://edulorenzo.spaces.live.com/blog/cns!7D19A0EE43408F6C!1044.entry ) where I added a Picture control to hold the preview. The you can take it from there by adding a YesNo messagebox to save or not.
Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

2 Responses to Cast WIA.Imagefile to System.Drawing.Image

  1. Mark ter Luun says:

    Wow! Thanks for this, I was looking into this for a while.. I was close, apparently; I just didn’t realize that the object returned by get_BinaryData() is just an array of bytes!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s