2009-05-29 172 views
1

您好我想创建一个转换器转换成我的图片在数据库中,数据类型“VARBINARY(最大)” 来填充我的DataGrid WPF中,但我有2个错误我告诉你的转换器:转换为图像的二进制WPF;

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

你能指出错误是什么吗? – ChrisF 2009-05-29 15:45:57

回答

2

如果值参数确实包含了类型的对象BinaryData那么你可以强制转换它:

Binary binaryData = (Binary)value; 

Binary binaryData = value as Binary; 

它可能会更好做的是 - 在投射之前检查数值参数,而不是在投射之后进行检查,就像现在一样。

+0

谢谢TomLog,没错:) – JayJay 2009-05-29 16:05:38