Posted By

firozjokhi on 07/20/12


Tagged

image MVC stream


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

BrockSamsom


Stream image from server and display it in view


 / Published in: C#
 

MVC action method to stream an image from the server and display it in the view

  1. //action to actually fetch the image
  2. [HttpGet]
  3. public ActionResult ShowImage()
  4. {
  5. byte[] image;
  6. var contentType = "image/png";
  7.  
  8. //get the image
  9. image = GetImageFromServer(@"..\Content\example.tif");
  10.  
  11. //convert from tiff to png
  12. var tiffStream = new MemoryStream(image);
  13. var pngStream = new MemoryStream();
  14. Bitmap.FromStream(tiffStream).Save(pngStream, ImageFormat.Png);
  15.  
  16. //return result
  17. return new ImageResult()
  18. {
  19. ImageStream = pngStream,
  20. MimeType = "image/png",
  21. Cacheability = HttpCacheability.NoCache
  22. };
  23. }
  24.  
  25.  
  26.  
  27. //get the image from the server (relative path)
  28. public byte[] GetImageFromServer(string name)
  29. {
  30. using (var stream = new FileStream(Server.MapPath(name), FileMode.Open))
  31. {
  32. var memoryStream = new MemoryStream();
  33. stream.CopyTo(memoryStream);
  34. return memoryStream.ToArray();
  35. }
  36. }
  37.  
  38.  
  39.  
  40.  
  41. //this is how to use it in your view to get the image
  42. <img src="@Url.Action("ShowImage","Home")">

Report this snippet  

You need to login to post a comment.