简体   繁体   English

通过RESTful Web服务返回图像

[英]Return image through RESTful webservice

I want to return an image through a web API call. 我想通过Web API调用返回图像。 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));
}

And then ideally, I would like be able to do something like this through the html... 然后理想情况下,我希望能够通过html执行类似的操作...

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

This obviously doesn't work. 这显然行不通。 Is there any way I can get this image tag to display a image returned by the RESTful service? 有什么方法可以获取此图像标签以显示RESTful服务返回的图像?

Does it have to be an api call? 是否必须是api调用?

I highly recommend using a generic handler for this. 我强烈建议为此使用通用处理程序。

Here's a little tutorial on it: http://www.dotnetperls.com/ashx 这是一个有关它的小教程: 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();

The image tag would be something along the lines of 图像标签可能类似于

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

I recommend you send image in base64 format 我建议您以base64格式发送图像

and set it to image 并将其设置为图像

<img src="data:image/gif;base64,<YOUR DATA>" alt="Base64 encoded image" />

URL to base64 you can use 您可以使用的base64的URL

public String ConvertImageURLToBase64(String url) 
{  
    StringBuilder _sb = new StringBuilder(); 

    Byte[] _byte = this.GetImage(url); 

    _sb.Append(Convert.ToBase64String(_byte, 0, _byte.Length));  
    return _sb.ToString();  
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM