4

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.

0

2 Answers 2

2

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; 

Sign up to request clarification or add additional context in comments.

Comments

1

I would start with the Maui CommunityToolkit which has wrappers around some of the most common operations - with that toolkit you can use the ByteArrayToImageSourceConverter - it should then be as simple as:

<Image Source="{Binding DotNetBotImageByteArray, Mode=OneWay, Converter={StaticResource ByteArrayToImageSourceConverter}}" />

https://github.com/MicrosoftDocs/CommunityToolkit/blob/main/docs/maui/markup/markup.md

https://github.com/MicrosoftDocs/CommunityToolkit/blob/main/docs/maui/converters/byte-array-to-image-source-converter.md

https://www.nuget.org/packages/CommunityToolkit.Maui

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.