tags:

views:

329

answers:

1

Hi I'm trying to create a converter to Convert my images in a database ,datatype"Varbinary(Max)" to populate my DataGrid in WPF but i have 2 error i show you the Converter:

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);
     }

 }

Cab you advice me if it is right or there is a better way to do this? Thanks for your help. Have a good Day

+1  A: 

If the value parameter does contain an object of the type BinaryData then you can just typecast it:

Binary binaryData =  (Binary)value;

or

Binary binaryData =  value as Binary;

It's probably better to do an is-null check on the value parameter before casting, rather than doing it after the cast, as you do now.

tomlog
Thanks TomLog,That's right:)
JayJay