Click here to Skip to main content
12,629,569 members (28,222 online)
Rate this:
Please Sign up or sign in to vote.
See more: C# WPF C#4.0
my code for convert image.source to byte[]

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 :

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

how to convert image1.Source to byte[] in wpf ?
Posted 3-Oct-12 2:21am
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.
Rate this: bad
Please Sign up or sign in to vote.

Solution 3

Just use the debugger to verify:
image1 != null
image1.Source != null
image1.Source is BitmapImage
or add
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.
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

If you are getting an Object Reference error, and the error is occuring on image1.Source, then likely image1 == null.

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

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web02 | 2.8.161205.3 | Last Updated 3 Oct 2012
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100