Конвертер двоичных изображений в WPF; - PullRequest
1 голос
/ 29 мая 2009

Привет! Я пытаюсь создать конвертер для преобразования моих изображений в базу данных, тип данных "Varbinary (Max)" заполнить мой DataGrid в 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 Ответ

2 голосов
/ 29 мая 2009

Если параметр value содержит объект типа BinaryData, вы можете просто ввести его:

Binary binaryData =  (Binary)value;

или

Binary binaryData =  value as Binary;

Вероятно, лучше выполнить проверку на значение null для параметра value перед приведением, чем делать это после преобразования, как вы делаете сейчас.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...