gpt4 book ai didi

c# - 使用 web api HttpResponseMessage 输出图像

转载 作者:IT王子 更新时间:2023-10-29 04:14:59 25 4
gpt4 key购买 nike

我正在尝试使用以下代码从 asp.net web api 输出图像,但响应正文长度始终为 0。

public HttpResponseMessage GetImage()
{
HttpResponseMessage response = new HttpResponseMessage();
response.Content = new StreamContent(new FileStream(@"path to image"));
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");

return response;
}

有什么建议吗?

作品:

    [HttpGet]
public HttpResponseMessage Resize(string source, int width, int height)
{
HttpResponseMessage httpResponseMessage = new HttpResponseMessage();

// Photo.Resize is a static method to resize the image
Image image = Photo.Resize(Image.FromFile(@"d:\path\" + source), width, height);

MemoryStream memoryStream = new MemoryStream();

image.Save(memoryStream, ImageFormat.Jpeg);

httpResponseMessage.Content = new ByteArrayContent(memoryStream.ToArray());

httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
httpResponseMessage.StatusCode = HttpStatusCode.OK;

return httpResponseMessage;
}

最佳答案

以下内容:

  1. 确保路径正确(duh)

  2. 确保您的路线正确。您的 Controller 是 ImageController,或者您定义了自定义路由以支持其他 Controller 上的“GetImage”。(你应该得到一个 404 响应。)

  3. 确保打开流:

    var stream = new FileStream(path, FileMode.Open);

我尝试了类似的东西,它对我有用。

关于c# - 使用 web api HttpResponseMessage 输出图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13001588/

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