Click here to Skip to main content
15,886,783 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
my code for convert image.source to byte[]

C#
public Byte[] BufferFromImage(BitmapImage imageSource)
{
    Stream stream = imageSource.StreamSource;
    Byte[] buffer = null;
    if (stream != null && stream.Length > 0)
    {
        using (BinaryReader br = new BinaryReader(stream))
        {
            buffer = br.ReadBytes((Int32)stream.Length);
        }
    }

    return buffer;
}


call :

C#
var s = BufferFromImage(image1.Source as BitmapImage);



how to convert image1.Source to byte[] in wpf ?
Posted
Comments
Kiran Susarla 3-Oct-12 7:54am    
Where are you getting NullReferenceException in the Code? Does imageSource parameter has any value? Did you check that while debugging?
Matt T Heffron 3-Oct-12 12:38pm    
Are you sure that image1.Source *IS* a BitmapImage? If it is not, then using "as BitmapImage" will return null and that will be passed to BufferFromImage.

Just use the debugger to verify:
C#
image1 != null
image1.Source != null
image1.Source is BitmapImage
or add
C#
System.Diagnostics.Debug.Assert(image1 != null, "image1 is null");
System.Diagnostics.Debug.Assert(image1.Source != null, 
                                "image1.Source is null");
System.Diagnostics.Debug.Assert(image1.Source is BitmapImage, 
                                "image1.Source is NOT a BitmapImage");
right before the call to BufferFromImage.
Then you should know what is wrong and how to fix it.
 
Share this answer
 
If you are getting an Object Reference error, and the error is occuring on image1.Source, then likely image1 == null.
 
Share this answer
 

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