通过RESTful webservice返回图像 [英] Return image through RESTful webservice

查看:117
本文介绍了通过RESTful webservice返回图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过Web API调用返回图像。我想要做的是获取图像,调整图像大小,然后返回它。这是我的代码......

I want to return an image through a web API call. What I am trying to do is get the image, resize the image, and then return it. Here is my code...

public Image GetImage(string url)
{
    WebClient wc = new WebClient();
    byte[] data = wc.DownloadData(url);
    MemoryStream memstream = new MemoryStream(data);
    Image img = Image.FromStream(memstream);
    img = resize(img, new System.Drawing.Size(100, 100));

    return img;
}

protected static System.Drawing.Image resize(System.Drawing.Image imgToResize, System.Drawing.Size size)
{
    return (System.Drawing.Image)(new System.Drawing.Bitmap(imgToResize, size));
}

然后理想情况下,我希望能够做到这样的事情通过html ...

And then ideally, I would like be able to do something like this through the html...

<img src="http://localhost:23520/Image/GetImage?url=whatever" />

这显然不起作用。有没有什么方法可以让这个图像标签显示RESTful服务返回的图像?

This obviously doesn't work. Is there any way I can get this image tag to display a image returned by the RESTful service?

推荐答案

是否必须是api电话?

Does it have to be an api call?

我强烈推荐使用通用处理程序。

I highly recommend using a generic handler for this.

这里有一个小教程: http://www.dotnetperls.com/ashx

你可以读入图像,将其保存到内存中,调整大小,然后直接输出图像。

You can read in the image, save it to memory, resize it, then output the image directly.

如果你确实去了处理程序路径,这会是你需要的代码

If you did go the handler route, this would be the code you needed

WebClient wc = new WebClient();
byte[] data = wc.DownloadData(context.Request.QueryString.Get("url"));
MemoryStream memstream = new MemoryStream(data);
Image img = Image.FromStream(memstream);
img = resize(img, new System.Drawing.Size(100, 100));
context.Response.Clear();
context.Response.ClearHeaders();
img.Save(context.Response.OutputStream, ImageFormat.Jpeg);
context.Response.ContentType = "image/jpeg";
HttpContext.Current.ApplicationInstance.CompleteRequest();

图片代码将是

< img src =http:// localhost:23520 / Image / GetImage.ashx?url = what/>

这篇关于通过RESTful webservice返回图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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