您好我正在尝试创建转换器以在数据库中转换我的图像,数据类型为“Varbinary(Max)” 在WPF中填充我的DataGrid,但我有2个错误,我向你展示转换器:
public class BinaryToImageConverter : IValueConverter
{
public object Convert(object value, System.Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
Binary binaryData = value;// here there is the first error .How convert BinaryData to Object??
if (binaryData == null) {
return null;
}
byte[] buffer = binaryData.ToArray();
if (buffer.Length == 0) {
return null;
}
BitmapImage res = new BitmapImage();
res.BeginInit();
res.StreamSource = new System.IO.MemoryStream(buffer);
res.EndInit();
return res;
}
public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
BitmapImage source = value;//How convert Bitmap to Object?
if (source == null) {
return null;
}
if ((source.StreamSource != null) && source.StreamSource.Length > 0) {
return GetBytesFromStream(source.StreamSource);
}
return null;
}
private Binary GetBytesFromStream(System.IO.Stream stream)
{
stream.Position = 0;
byte[] res = new byte[stream.Length + 1];
using (System.IO.BinaryReader reader = new System.IO.BinaryReader(stream)) {
reader.Read(res, 0, (int)stream.Length);
}
return new Binary(res);
}
}
出租车你建议我,如果它是正确的或有更好的方法来做到这一点? 谢谢你的帮助。 祝你有个美好的一天
答案 0 :(得分:2)
如果value参数确实包含BinaryData类型的对象,那么你可以对其进行类型转换:
Binary binaryData = (Binary)value;
或
Binary binaryData = value as Binary;
最好在转换之前对value参数执行is-null检查,而不是像现在一样在转换之后执行它。