My WP7 app has an Image control whose Source is set in XAML to an image with its Build Action set to Content:
<Image x:Name="MyImage" Source="/Images/myimage.png"/>
I need to store this image in my SqlCe database as a byte array. This is my current code to convert to byte[]:
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();
}
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:
public class BytesToImageConverter : IValueConverter {
public object Convert( object Value, Type TargetType, object Parameter, CultureInfo Culture ) {
if( Value != null && 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." );
}
}
I've done quite a bit of searching. As far as the converter, my code is pretty standard. I've seen mention that stream.Position = 0;
is necessary, but my understanding is stream.Seek
is doing the same thing; I've tried both.
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
BitmapImage image = MyImage.Source as BitmapImage;
without luck. I've been at this for hours and at my wit's end. What am I missing?