Youness Benbiga Youness Benbiga - 3 months ago 9
C# Question

Using Extensions to converte image from array of bits to bitmapimage in View

i need to call an extension in the view and not in my constructor so that i can see an image here my image

<Image Grid.Row="1"
Grid.Column="1"
Width="250"
Height="133"
HorizontalAlignment="Center"
Source="{Binding CitizenRegisterViewModel.CurrentDelegation.SignatureImage3.Content}" />


it's a array of bits

i found a converter :

public static BitmapImage ToBitmapImage(this byte[] byteArrayIn)
{

MemoryStream stream = new MemoryStream();
stream.Write(byteArrayIn, 0, byteArrayIn.Length);
stream.Position = 0;
System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
BitmapImage returnImage = new BitmapImage();
returnImage.BeginInit();
MemoryStream ms = new MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
ms.Seek(0, SeekOrigin.Begin);
returnImage.StreamSource = ms;
returnImage.EndInit();

return returnImage;


}


i would like to use it in the view is it possible because i m using the currentdelegation

Answer

Use this converter

public class ByteToBitmapImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        var bytes = value as byte[];
        if (bytes == null)
            throw new ArgumentNullException(nameof(value));

        return bytes.ToBitmapImage();
    }

    public static BitmapImage ToBitmapImage(this byte[] byteArrayIn)
    {

        MemoryStream stream = new MemoryStream();
        stream.Write(byteArrayIn, 0, byteArrayIn.Length);
        stream.Position = 0;
        System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
        BitmapImage returnImage = new BitmapImage();
        returnImage.BeginInit();
        MemoryStream ms = new MemoryStream();
        img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
        ms.Seek(0, SeekOrigin.Begin);
        returnImage.StreamSource = ms;
        returnImage.EndInit();

        return returnImage;


    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}

and update your view.

<Image Grid.Row="1"
       Grid.Column="1"
       Width="250"
       Height="133"
       HorizontalAlignment="Center"
       Source="{Binding CitizenRegisterViewModel.CurrentDelegation.SignatureImage3.Content,Converter={StaticResource ByteToBitmapImageConverter}}" />

And add your converter to page

<Page.Resources>
    <converters:ByteToBitmapImageConverter x:Key="ByteToBitmapImageConverter" />
</Page.Resources>