字节数组为WriteableBitmap图像IValueConverter为WP7
我一直在解决这个问题。 我从我的数据库中获取图像作为byte [],我想将其转换为WritableBitmap,所以我可以使用绑定在我的xaml页面上显示它。
我用这个:
public class ImageConverter : IValueConverter { /// /// Converts a Jpeg byte array into a WriteableBitmap /// public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value is byte[]) { MemoryStream stream = new MemoryStream((Byte[])value); WriteableBitmap bmp = new WriteableBitmap(200, 200); bmp.LoadJpeg(stream); return bmp; } else return null; } /// /// Converts a WriteableBitmap into a Jpeg byte array. /// public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } }
第一个问题是它不起作用。 当它命中bmp.LoadJpeg(stream);
时会抛出一个未指定的exceptionbmp.LoadJpeg(stream);
第二个问题是关于传递给WriteableBitmap构造函数的固定大小,我怎么知道来自db的照片大小? 我能以某种方式使它变得动态吗? 我想第二个问题是第一个问题的原因。
谢谢。
编辑
我也PictureDecoder.DecodeJpeg()
像这样使用PictureDecoder.DecodeJpeg()
:
MemoryStream stream = new MemoryStream((Byte[])value); WriteableBitmap bmp = PictureDecoder.DecodeJpeg(stream); return bmp;
但它也没有用。 在这种情况下, PictureDecoder.DecodeJpeg
假设为我创建bmp对象。 我仍然得到一个未指明的错误。 可能是我通过了流允许的最大长度?
我用它但它返回BitmapImage
。 你需要返回WriteableBitmap
吗?
编辑:如评论中提到的Ritch,如果你确实需要返回WriteableBitmap
add
var writeableBitmap = new WriteableBitmap(bitmapImage); return writeableBitmap
第二个问题是关于传递给WriteableBitmap构造函数的固定大小,我怎么知道来自db的照片大小?
创建BitmapImage后,您可以访问bitmapImage.PixelWidth
和bitmapImage.PixelHeight
。
public class ByteArraytoImageConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null) return null; var byteBlob = value as byte[]; var ms = new MemoryStream(byteBlob); var bmi = new BitmapImage(); bmi.SetSource(ms); return bmi; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } }
感谢您的回答
似乎问题是来自数据库的流以某种方式被破坏了。 价值转换器实际上还可以。 我已将其更改为使用PictureDecoder.DecodeJpeg()
因此它将更加干净和动态
public class ImageConverter : IValueConverter { /// /// Converts a Jpeg byte array into a WriteableBitmap /// public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value is byte[]) { MemoryStream stream = new MemoryStream((Byte[])value); WriteableBitmap bmp = PictureDecoder.DecodeJpeg(stream); return bmp; } else return null; } /// /// Converts a WriteableBitmap into a Jpeg byte array. /// public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } }