timeiscoffee
timeiscoffee

Reputation: 458

How do you get a image through external source in Web API and return it in base64?

I need to call a external API and retrieve a png image, and return that image in base64 string. How can I read response message as an image and convert it to base64?

This is what I have so far:

[HttpGet()]
[Route("test")]
public async Task<string> GetValidationImage()
{
   using (var client = new HttpClient())
   {
    //grab image from external API as png
    client.BaseAddress = new Uri(TestBaseAddress);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("image/png"));

    return response = await client.GetAsync(TestString);
   }
}

Upvotes: 2

Views: 2466

Answers (1)

timeiscoffee
timeiscoffee

Reputation: 458

Figured it out, had to stream it to an image object.

[HttpGet()]
[Route("test")]
public async Task<string> GetValidationImage()
{
   string base64String;
   client.BaseAddress = new Uri(TestBaseAddress);
   client.DefaultRequestHeaders.Accept.Clear();
   client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("image/png"));

   var response = await client.GetAsync(TestString);

   using (var ms = new MemoryStream())
   {
      var image = System.Drawing.Image.FromStream(await response.Content.ReadAsStreamAsync());
      image.Save(ms, ImageFormat.Png);
      var imageBytes = ms.ToArray();
      base64String = Convert.ToBase64String(imageBytes);
   }

   return base64String;
}

Upvotes: 2

Related Questions