Click here to Skip to main content
15,881,600 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
I scan a picture with wpfTwain. and display image into system.windows.control.image.

How do I convert the image to binary?

I used the following method

C#
public byte[] getJPGFromImageControl(BitmapImage imageC)
{
       MemoryStream memStream = new MemoryStream();              
        JpegBitmapEncoder encoder = new JpegBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(imageC));//error
        encoder.Save(memStream);
        return memStream.GetBuffer();
}




call as :

C#
getJPGFromImageControl(firmaUno.Source as BitmapImage)



error as : imageC is null !!!

why?

firmaUno.Source is not null !! but after the use from (firmaUno.Source as BitmapImage) ... BitmapImage is null!!!!

firmaUno.Source is system.windows.control.image
Posted
Comments
Sergey Alexandrovich Kryukov 9-Oct-12 13:02pm    
Why on Earth would you need BitmapImage?
--SA

1 solution

Here is why: http://msdn.microsoft.com/en-us/library/cscsdfbt%28v=vs.110%29.aspx[^].

Still did not get it? Look at "is equivalent to" line.

Still did not get it? Now, let's look at the definitions:
http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapimage.aspx[^].

As you can see, System.Windows.Media.ImageSource is the indirect base class of System.Windows.Media.Imaging.BitmapImage. It means, the BitmapImage is always ImageSource, but ImageSource is not always BitmapImage. Got it, finally? No?

Look, they are assignable like that:
C#
BitmapImage bitmap = //...
ImageSource src = bitmap;
but not in reverse direction. In reverse direction, you rightfully can use as. This operator returns null if unsuccessful and reference to the same object if successful, with the compile-time type of ImageSource and run-time type of BitmapImage. In your case, null indicated that your object is not BitmapImage.

Please see also my past answer: run-time polymorphism VS compile-time polymorphism[^].

Now, what to do? You simply should forget about BitmapImage, which you don't have and don't need. Any ImageSource can be serialized into array of bytes. Please see:
http://social.msdn.microsoft.com/forums/en-US/wpf/thread/8327dd31-2db1-4daa-a81c-aff60b63fee6/[^].

Please see this CodeProject article on TWAIN for WPF: Twain for WPF Applications - Look Ma, No Handles[^].

—SA
 
Share this answer
 
v6
Comments
RaisKazi 9-Oct-12 13:28pm    
My 5.
Sergey Alexandrovich Kryukov 9-Oct-12 13:32pm    
Thank you, Rais.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900