Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get image as byte array from web API and display it in .Net Maui application

I am calling a web API that sends back an image as a byte array. I want to show it on a form in .net Maui. I am using MVVM pattern.

I tried setting up an ImgToShow property as a byte array and set the binding of the Image control on the form to it. Doesnt work.

I tried saving the image to FileSystem.Current.AppDataDirectory and set the source of the image control to full path of the image. Doesnt work.

How does one show an image like this. Lots of examples about using FromUri as image source for image control but did not find anything much about when retrieving image as a byte array and showing it in the image control.

Kindly help.

like image 483
MethodToChaos Avatar asked Nov 01 '25 11:11

MethodToChaos


1 Answers

I have been handling this in the code behind

  1. You need to convert the byte array to a MemoryStream.
  2. From there you can get the ImageSource.
  3. Then just set that to the source of your image.
// get your byte array
byte[] byteArray = GetByteArrayFromApi();

// convert it to a memory stream
MemoryStream mStream = new MemoryStream(byteArray);

// create image source from the memory stream
ImageSource myImageSource = ImageSource.FromStream(() => mStream);

// add the source to your image element 
image.Source = myImageSource; 

like image 136
Jeff Avatar answered Nov 04 '25 04:11

Jeff