title: How to convert Image.Source to byte array?
body: <p>My WP7 app has an Image control whose Source is set in XAML to an image with its Build Action set to Content:</p>
  
  <pre><code>&lt;Image x:Name="MyImage" Source="/Images/myimage.png"/&gt;
  </code></pre>
  
  <p>I need to store this image in my SqlCe database as a byte array. This is my current code to convert to byte[]:</p>
  
  <pre><code>public byte[] ImageToArray() {
      BitmapImage image = new BitmapImage();
      image.CreateOptions = BitmapCreateOptions.None;
      image.UriSource = new Uri( "/Images/myimage.png", UriKind.Relative );
      WriteableBitmap wbmp = new WriteableBitmap( image );
      return wbmp.ToArray();
  }
  </code></pre>
  
  <p>The byte array saves to the database, but when I retrieve and my converter tries to convert it back (on a different page), I get "unspecified error." This is my converter:</p>
  
  <pre><code>public class BytesToImageConverter : IValueConverter {
      public object Convert( object Value, Type TargetType, object Parameter, CultureInfo Culture ) {
          if( Value != null &amp;&amp; Value is byte[] ) {
              byte[] bytes = Value as byte[];
  
              using( MemoryStream stream = new MemoryStream( bytes ) ) {
                  stream.Seek( 0, SeekOrigin.Begin );
  
                  BitmapImage image = new BitmapImage();
                  image.SetSource( stream ); // Unspecified error here
                  return image;
              }
          }
  
          return null;
      }
  
      public object ConvertBack( object Value, Type TargetType, object Parameter, CultureInfo Culture ) {
          throw new NotImplementedException( "This converter only works for one way binding." );
      }
  }
  </code></pre>
  
  <p>I've done quite a bit of searching. As far as the converter, my code is pretty standard. I've seen mention that <code>stream.Position = 0;</code> is necessary, but my understanding is <code>stream.Seek</code> is doing the same thing; I've tried both.</p>
  
  <p>As my converter is the same I've used in about a dozen projects now, I'm fairly convinced the problem lies in converting the Image control's Source to a byte array and thus my image data is corrupted. In the code above I'm hard coding the Uri, but I've also tried</p>
  
  <pre><code>BitmapImage image = MyImage.Source as BitmapImage;
  </code></pre>
  
  <p>without luck. I've been at this for hours and at my wit's end. What am I missing?</p>