Yanshof
Yanshof

Reputation: 9926

How to Convert system.windows.controls.image to byte[]

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

How to do it ?

Upvotes: 0

Views: 3901

Answers (3)

Ejrr1085
Ejrr1085

Reputation: 1071

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();
}

Upvotes: 1

Marcel
Marcel

Reputation: 15722

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

Upvotes: 1

Brian Scott
Brian Scott

Reputation: 9361

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();
}

Upvotes: 1

Related Questions