title: BitmapImage to byte[] - C# web
body: <p>I need to convert a BitmapImage in a byte[] but I don't find how to do it in C# web.
  I found examples but none of them work (JpegBitmapEncoder doesn't exist, BitmapImageObject.StreamSource doesn't exist, there isn't WriteableBitmap constructor with BitmapImage as parameter, Extensions.SaveJpeg(<em>parameters</em>) doesn't exist ...).</p>
  
  <p>Examples I found:</p>
  
  <p>Constructor <em>new WriteableBitmap(bitmapImage)</em> doesn't exist.</p>
  
  <pre><code>public static byte[] ConvertToBytes(this BitmapImage bitmapImage)
  {
      byte[] data;
      // Get an Image Stream
      using (MemoryStream ms = new MemoryStream())
      {
          WriteableBitmap btmMap = new WriteableBitmap(bitmapImage);
  
          // write an image into the stream
          Extensions.SaveJpeg(btmMap, ms,
              bitmapImage.PixelWidth, bitmapImage.PixelHeight, 0, 100);
  
          // reset the stream pointer to the beginning
          ms.Seek(0, 0);
          //read the stream into a byte array
          data = new byte[ms.Length];
          ms.Read(data, 0, data.Length);
      }
      //data now holds the bytes of the image
      return data;
  }
  </code></pre>
  
  <hr>
  
  <p><em>new WriteableBitmap(img)</em>, <em>System.Windows.Media.Imaging.Extensions.SaveJpeg</em> don't exist.</p>
  
  <pre><code>public static byte[] ImageToBytes(BitmapImage img)
  {
      using (MemoryStream ms = new MemoryStream())
      {
          WriteableBitmap btmMap = new WriteableBitmap(img);
          System.Windows.Media.Imaging.Extensions.SaveJpeg(btmMap, ms, img.PixelWidth, img.PixelHeight, 0, 100);
          img = null;
          return ms.ToArray();
      }
  }
  </code></pre>
  
  <hr>
  
  <p><em>imageSource.StreamSource</em> doesn't exist.</p>
  
  <pre><code>public static byte[] ImageToByte(BitmapImage imageSource)
  {
      Stream stream = imageSource.StreamSource;
      Byte[] buffer = null;
      if (stream != null &amp;&amp; stream.Length &gt; 0)
      {
          using (BinaryReader br = new BinaryReader(stream))
          {
              buffer = br.ReadBytes((Int32)stream.Length);
          }
      }
  
      return buffer;
  }
  </code></pre>
  
  <hr>
  
  <p><em>JpegBitmapEncoder</em> doesn't exist.</p>
  
  <pre><code>byte[] data;
  JpegBitmapEncoder encoder = new JpegBitmapEncoder();
  encoder.Frames.Add(BitmapFrame.Create(bitmapImage));
  using(MemoryStream ms = new MemoryStream())
  {
      encoder.Save(ms);
      data = ms.ToArray();
  }
  </code></pre>