Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert A Byte[] Array to Image in Xamarin Forms

Before asking this question I googled a lot but couldn't find a solution that suits mine.

In Xamarin.Forms I have a byte[] array and I want to Convert that byte[] array to an Image. How can I achieve that, this is what I tried:

In Front End(XAML):

<StackLayout BackgroundColor="Olive" x:Name="imagePanel">
    <Image x:Name="PdfImage" Aspect="AspectFill" IsVisible="true"/>
</StackLayout>   

In Code Behind(C#):

byte[] imageAsBytes = Constant.jsonPDF;

var stream1 = new MemoryStream(imageAsBytes);
PdfImage.Source = ImageSource.FromStream(() => new MemoryStream(imageAsBytes));

imagePanel.Children.Add(PdfImage);

But My problem is image is not displaying.

Can anybody tell me what I'm doing wrong. Any help would be greatly appreciated.

like image 274
Jestin Saji Chacko Avatar asked Dec 06 '16 19:12

Jestin Saji Chacko


3 Answers

(XAML):

 <Image Grid.Row="1" x:Name="IncidentImageData" Grid.ColumnSpan="4" BackgroundColor="DarkGray" Aspect="AspectFill" WidthRequest="50" HeightRequest="175"/> 

viewModel.SImageBase64 is a byte[]

Code Behind(C#):

var stream1 = new MemoryStream(viewModel.SImageBase64);
IncidentImageData.Source = ImageSource.FromStream(() => stream1);

simply i have done like this and image has shown.

like image 129
Ganesh Kumar Avatar answered Oct 19 '22 19:10

Ganesh Kumar


A Potential Fix

I know this thread is 2 years old now but I thought i'd post a working solution here for anyone who's also struggling with this. Just spent half a day researching and trying to solve an identical problem, the way the code was written on this post helped me greatly as it is almost 100% correct. You just need to provide the MemoryStream as a return from a lambda function within the FromStream() method.

Change this:

PdfImage.Source = ImageSource.FromStream(() => new MemoryStream(imageAsBytes));

To:

PdfImage.Source = ImageSource.FromStream(() =>
{
     return new MemoryStream(imageAsBytes);
});

And the snippet should be working as of Xamarin Forms 5.0.0.2012

Full Code:

byte[] imageAsBytes = Constant.jsonPDF;

PdfImage.Source = ImageSource.FromStream(() =>
{
     return new MemoryStream(imageAsBytes);
});

imagePanel.Children.Add(PdfImage);
like image 37
Matthew Swallow Avatar answered Oct 19 '22 20:10

Matthew Swallow


Use this Code :

imgUserImage.Source = ImageSource.FromStream(() => new MemoryStream(userList.Single().ProfilePhoto));

Here profile photo type is byte[]

public byte[] ProfilePhoto { get; set; }
like image 4
Chandra Shakar Avatar answered Oct 19 '22 21:10

Chandra Shakar