代码之家  ›  专栏  ›  技术社区  ›  JayJay

转换二进制到图像WPF;

  •  1
  • JayJay  · 技术社区  · 16 年前

    嗨,我正在创建一个转换器来转换数据库中的图像,数据类型“varbinary(max)”。 要在WPF中填充我的数据报,但我有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);
         }
    
     }
    

    如果是对的,或者有更好的方法,你会给我提建议吗? 谢谢你的帮助。 祝您今天过得愉快

    1 回复  |  直到 10 年前
        1
  •  2
  •   Tom van Enckevort    16 年前

    如果value参数确实包含binarydata类型的对象,则可以对其进行类型转换:

    Binary binaryData =  (Binary)value;
    

    Binary binaryData =  value as Binary;
    

    在强制转换之前,最好对值参数进行IS NULL检查,而不是像现在这样在强制转换之后进行检查。