0

I need to convert System.Windows.Controls.Image to byte[].

How to do it ?

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
Yanshof
  • 9,659
  • 21
  • 95
  • 195
  • 5
    Are you sure you are trying to convert a 'system.windows.controls.image' and not simply the 'System.Drawing.Image' that it displays instead? – Brian Scott Mar 24 '11 at 12:18
  • @Brian It's WPF, so the class that contains the actual image is `System.Windows.Media.ImageSource` and not `System.Drawing.Image` – CodesInChaos Mar 24 '11 at 12:24

3 Answers3

1

Assuming that you answer my query above that you are actually trying to convert an image into a byte array rather than an image control into a byte array here is the code to do so;

public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
 MemoryStream ms = new MemoryStream();
 imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
 return  ms.ToArray();
}
Brian Scott
  • 9,221
  • 6
  • 47
  • 68
1

In general, to convert an object to a byte array, you may want to use binary serialization. This will generate a memory stream from which you can extract a byte array.
You may start with this Question and Answer

Community
  • 1
  • 1
Marcel
  • 15,039
  • 20
  • 92
  • 150
1
System.Windows.Controls.Image img = new System.Windows.Controls.Image();
var uri = new Uri("pack://application:,,,/Images/myImage.jpg");
img.Source = new BitmapImage(uri);
byte[] arr;
using (MemoryStream ms = new MemoryStream())
{
      var bmp = img.Source as BitmapImage;
      JpegBitmapEncoder encoder = new JpegBitmapEncoder();
      encoder.Frames.Add(BitmapFrame.Create(bmp));
      encoder.Save(ms);
      arr = ms.ToArray();
}
Ejrr1085
  • 975
  • 2
  • 16
  • 29