Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I bind a Byte array to an Image in WPF with a value converter?

I'm trying to bind a Byte array from my databse to a WPF Image.

My XAML:

<Window.Resources>
    <local:BinaryImageConverter x:Key="imgConverter" />
</Window.Resources>
...
<Image Source="{Binding Path=ImageData, Converter={StaticResource imgConverter}}" />

I've modified code published by Ryan Cromwell for a value converter:

Class BinaryImageConverter
    Implements IValueConverter
    Private Function Convert(ByVal value As Object, ByVal targetType As Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements IValueConverter.Convert
        If value IsNot Nothing AndAlso TypeOf value Is Byte() Then
            Dim bytes As Byte() = TryCast(value, Byte())
            Dim stream As New MemoryStream(bytes)
            Dim image As New BitmapImage()
            image.BeginInit()
            image.StreamSource = stream
            image.EndInit()
            Return image
        End If
        Return Nothing
    End Function
    Private Function ConvertBack(ByVal value As Object, ByVal targetType As Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements IValueConverter.ConvertBack
        Throw New Exception("The method or operation is not implemented.")
    End Function
End Class

The image.EndInit() line of the BinaryImageConverter's Convert() function throws this NotSupportedException:

"No imaging component suitable to complete this operation was found."

InnerException: "Exception from HRESULT: 0x88982F50"

I don't understand what I'm doing wrong. How can I get this working?


Update

It seems the problem was the bytes coming out of the database. There must have been a problem with the way I was putting them in.

See my working code below.

like image 542
Zack Peterson Avatar asked Mar 26 '09 16:03

Zack Peterson


1 Answers

You can bind a byte[] to an Image.

Here a Sample:

Xaml:

<Image Source="{Binding UserImage}"/>

Code:

private byte[] userImage;

public byte[] UserImage
   {
       get { return userImage; }
       set
       {
           if (value != userImage)
           {
               userImage = value;
               OnPropertyChanged("UserImage");
           }
       }
   }
like image 97
sebastianb Avatar answered Oct 02 '22 22:10

sebastianb