gpt4 book ai didi

c# - 从 WebApi 返回图像

转载 作者:太空狗 更新时间:2023-10-29 21:56:51 24 4
gpt4 key购买 nike

我正在制作一个 Web Api,我需要向客户端返回多个图像。我目前正在为每个图像使用 Base64 字符串,但这会导致每个请求花费的时间太长。是否有更好、更高效的图片返回方式?

这是我使用的代码:

Controller :

    public LearningUnits GetLearningUnits([FromODataUri]Guid key)
{
var record = db.LearningUnits.SingleOrDefault(inst => inst.LearningUnitId == key);

record.ImageURLPath = ImageHandler.ImageToByteArrayFromFilePath(record.ImageURLPath);

return record;
}

ImageToByteArray 方法:

    public static string ImageToByteArrayFromFilePath(string imagefilePath)
{
byte[] imageArray = File.ReadAllBytes(imagefilePath);

string baseImage = Convert.ToBase64String(imageArray);

return baseImage;
}

最佳答案

如果端点返回 json,那么除了 base64 之外,没有其他方法可以在响应中嵌入二进制文件。但由于性能问题,这绝对不是一个好主意。可能对于某些图标来说没问题,但对于较大的图像就不合适了。

所以这里最好的解决方案是将 url 返回到图像。客户端将进一步请求获取图像的原始字节。

另外值得一提的是,图像 url 不仅可以是静态文件的路径,还可以是一些 webapi 端点的路径,例如,通过资源 id 获取图像字节并发送客户端原始二进制文件返回,而不是 json 字符串。

关于c# - 从 WebApi 返回图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36770334/

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