karunakar bhogyari
karunakar bhogyari

Reputation: 679

How to download Image[Call API, API returns byte[] of image] from server and show it in contentpage in xamarin forms

  1. Call Rest service
  2. Rest service returns byte[] representation of image/audio/video
  3. convert into byte[] to image and show in content page in xamarin

Upvotes: 0

Views: 986

Answers (1)

Sparsha Bhattarai
Sparsha Bhattarai

Reputation: 703

First of all, you can create a function that simply makes an API request and obtains the content in the form of byte array. A simple example of HTTP request:

  public static byte[] GetImageByteArray(string url)
    {
        try
        {
            using (var client = new HttpClient())
            {
                var uri = new Uri(url);
                var response = client.GetAsync(uri).Result;
                if (response.IsSuccessStatusCode)
                {
                    var content = response.Content.ReadAsByteArrayAsync();
                    return content.Result;
                }
            }
            return null;
        }
        catch
        {
            return null;
        }
    }

Next, you can simply bind the output from your result into your image source and the image to your content:

var mainStack = new StackLayout();
var imageByteArray = GetImageByteArray("https://static.pexels.com/photos/34950/pexels-photo.jpg");
Image image;
if (imageByteArray != null)
{
    image = new Image()
    {
        Source = ImageSource.FromStream(() => new MemoryStream(imageByteArray))
    };

    mainStack.Children.Add(image);
}
Content = mainStack;

Upvotes: 1

Related Questions