【问题标题】:Return image from API - not using Core从 API 返回图像 - 不使用核心
【发布时间】:2018-07-24 02:36:17
【问题描述】:

我一直在试图弄清楚如何从 API 返回图像。我看到了最接近的this answer,但我认为它使用了我没有使用的核心。我想出的最好的是

    // GET: api/Documents/GetImage/ZJvNmUw991B-KOFj4rAf6ApkYOYuxfgZptZcQlk_k7nK0ZNFr7FGpfLdZZOYcLmXBAuYHWImnV8gCIezYfb9Rw2
    [ActionName("GetImage")]
    [ResponseType(typeof(Byte[]))]
    [HttpGet]
    public IHttpActionResult GetImage(string parameter)
    {
        Bitmap icon = new Bitmap(500, 100);
        Graphics g = Graphics.FromImage(icon);
        RectangleF rectf = new RectangleF(70, 90, 90, 50);
        g.DrawString("Hello World!", new Font("Tahoma", 8), Brushes.Black, rectf);
        g.Flush();

        using (MemoryStream memStream = new MemoryStream())
        {
            icon.Save(memStream, ImageFormat.Bmp);
            return Ok(memStream.ToArray());
        }
    }

它确实返回数据,但作为字节数组。如何告诉 Ok Action 结果以“image/bmp”的内容类型发回?

在 api 测试工具中,我可以将请求发送到 http://localhost:58173/api/Documents/GetImage/2,然后我得到 [200 OK] 的响应,其响应内容为“Qk12DQMAAAAAAADYAAAAAOAAAA9AEAAGQAAAA...”,这显然只是位图的字节数组表示。当我在这样的 html 中使用它时

    <img src="http://localhost:58173/api/Documents/GetImage/2" />

无法显示图像。我认为它不会将该字节流识别为图像......因为它从未返回内容类型?

我做错了什么?

【问题讨论】:

  • @RalfBönning - 我看过那个,但我一直蹲着。刚刚发现我没有得到图像的原因是因为在将内存流用于响应之前我没有将内存流重置为零位置。

标签: c# image api return-type


【解决方案1】:

你可以返回一个FileStreamResult,例如:

return new FileStreamResult(memStream, "image/bmp");

【讨论】:

  • 似乎有同样的问题,返回的结果只是被视为文件流。内容类型似乎不会返回。我的 API 测试工具给了我 [200 OK] 和 {"FileStream": {"_buffer": Qk12DQMAAA... 的响应正文
  • 您是否将其包装在 Ok(...) 中?
  • 没有。我只是将方法的签名更改为使用 FileStreamResult 作为类型,并将 return 语句更改为您建议的内容。
【解决方案2】:

所以,我又返回了一个 HttpResponseMessage,但有一些非常重要的变化——当我之前尝试它时,这些问题让我很生气......

通过对内存流执行using (MemoryStream memStream = new Mem...,我导致它在响应实际发回之前被处理掉,因此响应试图从不再存在的内存流中构建消息。

另外,我没有将内存流倒回到零位置,因此响应消息会得到全部内容。

这是运行的结果代码...

    [ActionName("GetImage")]
    [HttpGet]
    public HttpResponseMessage GetImage(string parameter)
    {
        using (Bitmap icon = new Bitmap(500, 100))
        {

            Graphics g = Graphics.FromImage(icon);
            RectangleF rectf = new RectangleF(10,10,480,80);
            g.DrawString("Hello World!", new Font("Tahoma", 20), Brushes.White, rectf);
            g.Flush();

            HttpResponseMessage responseMessage = Request.CreateResponse();
            MemoryStream memStream = new MemoryStream();
            icon.Save(memStream, ImageFormat.Bmp);
            memStream.Position = 0;
            responseMessage.Content = new StreamContent(memStream);
            responseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("image/bmp");
            return responseMessage;
        }
    }

唯一的问题是,这让我担心我会留下一个内存流,而不是被处理掉。还是 HttpResponseMessage 类在使用后将其处理掉?我想我在寻找这个答案时在某处读到它确实做到了。

【讨论】:

  • 嗯,有人认为你可以清理usingBitmap对象。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多