是否有推荐的方法使用 ASP.NET Web API 返回图像 [英] Is there a recommended way to return an image using ASP.NET Web API

查看:37
本文介绍了是否有推荐的方法使用 ASP.NET Web API 返回图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

返回带有 2 个参数(用于调整大小的 x 和 y)的图像的最佳方法是什么.

What is the best way to return an image with 2 parameters (x and y for resize).

例如

~/api/image12345/200/200

将返回 200 x 200 jpg/png/或 gif

Will return a 200 by 200 jpg/png/or gif

我应该返回一个System.Drawing.Image 对象还是手动定义HTTPReponseMessage.Content?

Should I return a System.Drawing.Image object or manually define the HTTPReponseMessage.Content?

推荐答案

您不应返回 System.Drawing.Image,除非您还添加了一个知道如何将其转换为适当的字节不会像您期望的那样将自身序列化为图像字节.

You shouldn't return a System.Drawing.Image, unless you also add a formatter which knows how to convert that into the appropriate bytes doesn't serialize itself as the image bytes as you'd expect.

一种可能的解决方案是返回一个 HttpResponseMessage 并在其内容中存储图像(如下所示).请记住,如果您想要在问题中显示的 URL,您需要一个映射 {imageName}、{width} 和 {height} 参数的路由.

One possible solution is to return an HttpResponseMessage with the image stored in its content (as shown below). Remember that if you want the URL you showed in the question, you'd need a route that maps the {imageName}, {width} and {height} parameters.

public HttpResponseMessage Get(string imageName, int width, int height)
{
    Image img = GetImage(imageName, width, height);
    using(MemoryStream ms = new MemoryStream())
    {
        img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
        result.Content = new ByteArrayContent(ms.ToArray());
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");

        return result;
    }
}

但同样,如果你在很多地方都这样做,走格式化程序路线可能是推荐"的方式.正如编程中的几乎所有内容一样,答案将取决于您的场景.

But again, if you are doing this in many places, going the formatter route may be the "recommended" way. As almost everything in programming, the answer will depend on your scenario.

这篇关于是否有推荐的方法使用 ASP.NET Web API 返回图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆