Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle Images using WebAPI

Questions

  1. What are the different ways to POST/GET images to my service? I think I can either use Base-64 text in JSON or stay native as binary. My understanding is that by converting the image into text, there is a significant increase is package size.

  2. If I send the image (from a web form, from a native client, from another service), should I add a Image Controller/Handler or use a Formatter? Is this even an either/or question?

I have researched and found many competing examples but I am not sure which direction I should be heading.

Is there a site/blog article that lays out the pros and cons for this?

like image 210
Jamie Dixon Avatar asked Sep 25 '13 13:09

Jamie Dixon


People also ask

How do I find the Image API response?

To get an image from API with JavaScript Fetch API, we can call the response's blob method and use the FileReader to read the file into a base64 string. We create the FileReader instance and set the onloadend property to a function that gets the base64 string from reader. result .

How do I get image results back from Web API?

It's better to use the File method overload which accepts a stream, this way you don't to load the picture into the servers memory before sending it. FileStream stream = File. Open(@"E:\\Test. jpg"); return File(stream, "image/jpeg"); or even easier: return PhysicalFile("@E:\\Test.


2 Answers

I did some research and you can see the implementation I came up with here: http://jamessdixon.wordpress.com/2013/10/01/handling-images-in-webapi/

like image 93
Jamie Dixon Avatar answered Sep 20 '22 00:09

Jamie Dixon


For preservation's sake - here's the outline of what Jamie's blog said:

Use a Controller:

Get:

public HttpResponseMessage Get(int id) {     var result = new HttpResponseMessage(HttpStatusCode.OK);     String filePath = HostingEnvironment.MapPath("~/Images/HT.jpg");     FileStream fileStream = new FileStream(filePath, FileMode.Open);     Image image = Image.FromStream(fileStream);     MemoryStream memoryStream = new MemoryStream();     image.Save(memoryStream, ImageFormat.Jpeg);     result.Content = new ByteArrayContent(memoryStream.ToArray());     result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");      return result; } 

Delete:

public void Delete(int id) {     String filePath = HostingEnvironment.MapPath("~/Images/HT.jpg");     File.Delete(filePath); } 

Post:

public HttpResponseMessage Post() {     var result = new HttpResponseMessage(HttpStatusCode.OK);     if (Request.Content.IsMimeMultipartContent())     {         //For larger files, this might need to be added:         //Request.Content.LoadIntoBufferAsync().Wait();         Request.Content.ReadAsMultipartAsync<MultipartMemoryStreamProvider>(                 new MultipartMemoryStreamProvider()).ContinueWith((task) =>         {             MultipartMemoryStreamProvider provider = task.Result;             foreach (HttpContent content in provider.Contents)             {                 Stream stream = content.ReadAsStreamAsync().Result;                 Image image = Image.FromStream(stream);                 var testName = content.Headers.ContentDisposition.Name;                 String filePath = HostingEnvironment.MapPath("~/Images/");                 //Note that the ID is pushed to the request header,                 //not the content header:                 String[] headerValues = (String[])Request.Headers.GetValues("UniqueId");                 String fileName = headerValues[0] + ".jpg";                 String fullPath = Path.Combine(filePath, fileName);                 image.Save(fullPath);             }         });         return result;     }     else     {         throw new HttpResponseException(Request.CreateResponse(                 HttpStatusCode.NotAcceptable,                 "This request is not properly formatted"));     }  } 
like image 24
Aske B. Avatar answered Sep 23 '22 00:09

Aske B.