使用Web API HttpResponseMessage输出图像

29

我正在尝试使用以下代码从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;
    }

我不太确定我是否理解了您的意思 - 但是您可以查看如何将图像写入输出流 - Pilgerstorfer Franz
我没有收到任何错误信息,也没有得到任何东西。 - lolol
你得到了什么状态码? - Maggie Ying
1
我知道这是一篇旧帖子,但你应该更新你的示例以正确处理垃圾回收,这样那些可能会复制/粘贴到他们的应用程序中的新手才能受益。 - Christopher Davies
我们如何使用端点在 .net core web 应用程序上显示图像?在浏览器上似乎只需要端点本身就可以加载图像。 - Avinash Prabhakar
2个回答

5
以下内容:
  1. 确保路径正确(显然)

  2. 确保路由正确。要么您的控制器是ImageController,要么您定义了一个自定义路由来支持其他控制器上的“GetImage”。 (对于此,您应该收到404响应。)

  3. 确保您打开流:

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

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


2

除了使用ByteArrayContent,您还可以使用StreamContent类来更有效地处理流。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接