Showing images from database in in Silverlight

You can show images in Silverlight using Image control.  You can furthermore bind Source property of the image to byte[] type property of a business object.  You would think this is sufficient, but it is not.  You will need a converter to convert byte array into image source.

Here is the class for converter

public class ImageSourceConverter : IValueConverter
{

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        BitmapImage bitmap = new BitmapImage();
        bitmap.SetSource(new MemoryStream((Byte[])value));
        return bitmap;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Here is how this class is used in a control:

<UserControl.Resources>
       <helpers:ImageConverter x:Key="ConvertImage"/>
   </UserControl.Resources>

<Image Source="{Binding Path=MyByteArrayPropertyName, Converter={StaticResource ConvertImage}}" />

9 Comments

  1. ‘helpers’ is unknown, i got that message : the type ‘helpers:ImageConverter’ was not found. Verify that you are not missing an assembly reference and that all referenced assemblies have been built
    any idea please. thanks

  2. Thanks for your reply.
    I can’t import the Helpers namespace, when I try to add it by: ‘ xmlns:src=”clr-namespace:BusinessApplication1.Helpers”
    I got that message: “Undefined CLR namespace, The ‘clr-namespace’ URI refers to a namespace ‘BusnissApplication1.Helpers’ that is not included in the assembly”

  3. @Soukaina
    Instead of pasting it in, just types xmlns:helpers= and let the intellisense fill in the rest. Your namepaces are wrong I think. Without the project I cannot really do much more.

  4. doesn’t fill the rest :(, I don’t know where’s the problem
    Please how can I send you my project to check it.
    I really need to solve it as soon as possible.
    thanks in advance for your help

Leave a Reply to Soukaina Cancel reply

Your email address will not be published. Required fields are marked *