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

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

问题描述

我与ASP.NET网页API玩弄周围,我很好奇,最好的办法有两个参数(x和y的大小调整)返回一个影像。

I'm toying around with ASP.NET Web Api and I'm curious as to the best way to return an image with 2 parameters (x and y for resize).

例如

~/api/image12345/200/200

会返回200 200 JPG / PNG / GIF或

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

我应该返回一个为System.Drawing.Image对象或手动定义HTT preponseMessage.Content?哪种方式是最有效的和低的开销。

Should I return a System.Drawing.Image object or manually define the HTTPReponseMessage.Content? Which way is the most efficient and low on overhead.

推荐答案

您不应该返回一个为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.

一个可能的解决方案是用存储在其内容的图像返回的Htt presponseMessage (如下图所示)。请记住,如果你想你的问题显示的URL,你需要映射的{} imageName的路线,{宽度}和{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);
        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天全站免登陆