gpt4 book ai didi

c# - 如何在 Web API 中通过外部源获取图像并以 base64 返回?

转载 作者:太空宇宙 更新时间:2023-11-03 10:43:08 26 4
gpt4 key购买 nike

我需要调用外部 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);
}
}

最佳答案

弄清楚了,必须将其流式传输到图像对象。

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

关于c# - 如何在 Web API 中通过外部源获取图像并以 base64 返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24565057/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com