Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将二进制图像转换为WPF;_C#_.net_Wpf - Fatal编程技术网

C# 将二进制图像转换为WPF;

C# 将二进制图像转换为WPF;,c#,.net,wpf,C#,.net,Wpf,嗨,我正在尝试创建一个转换器来转换数据库中的图像,数据类型为“Varbinary(Max)” 要在WPF中填充我的DataGrid,但我有2个错误,我向您展示了转换器: public class BinaryToImageConverter : IValueConverter { public object Convert(object value, System.Type targetType, object parameter, System.Globalization.Cultur

嗨,我正在尝试创建一个转换器来转换数据库中的图像,数据类型为“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);
     }

 }
你能告诉我这是对的还是有更好的方法? 谢谢你的帮助。
祝您愉快

如果value参数确实包含BinaryData类型的对象,则您可以直接键入它:

Binary binaryData =  (Binary)value;


可能最好在强制转换之前对value参数执行is null检查,而不是像现在这样在强制转换之后执行。

您能指出错误是什么吗?
Binary binaryData =  value as Binary;