Reputation: 2653
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));
}
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" />
This obviously doesn't work. Is there any way I can get this image tag to display a image returned by the RESTful service?
Upvotes: 1
Views: 19659
Reputation: 748
I recommend you send image in base64 format
and set it to image
<img src="data:image/gif;base64,<YOUR DATA>" alt="Base64 encoded image" />
URL to base64 you can use
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();
}
Upvotes: 1
Reputation: 9224
Does it have to be an api call?
I highly recommend using a generic handler for this.
Here's a little tutorial on it: 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" />
Upvotes: 3