如何通过Web API中的外部源获取图像并将其返回到base64?

时间:2014-07-04 00:15:51

标签: c# asp.net asp.net-web-api

我需要调用外部API并检索png图像,并以base64字符串形式返回该图像。如何将响应消息作为图像读取并将其转换为base64?

这是我到目前为止所做的:

[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);
   }
}

1 个答案:

答案 0 :(得分:2)

想出来,不得不将它流式传输到图像对象。

[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;
}