16

How can I make a controller method called GetMyImage() which returns an image as the response (that is, the content of the image itself)?

I thought of changing the return type from ActionResult to string, but that doesn't seem to work as expected.

Mathias Lykkegaard Lorenzen
  • 14,077
  • 22
  • 91
  • 177

5 Answers5

20

Return FilePathResult using File method of controller

public ActionResult GetMyImage(string ImageID)
{
    // Construct absolute image path
    var imagePath = "whatever";

    return base.File(imagePath, "image/jpg");
}

There are several overloads of File method. Use whatever is most appropriate for your situation. For example if you wanted to send Content-Disposition header so that the user gets the SaveAs dialog instead of seeing the image in the browser you would pass in the third parameter string fileDownloadName.

amit_g
  • 29,985
  • 8
  • 58
  • 117
4

Check out the FileResult class. For example usage see here.

Community
  • 1
  • 1
Nate
  • 29,508
  • 21
  • 110
  • 179
4

You can use FileContentResult like this:

byte[] imageData = GetImage(...); // or whatever
return File(imageData, "image/jpeg");
kprobst
  • 15,555
  • 5
  • 30
  • 53
2
using System.Drawing;
using System.Drawing.Imaging;     
using System.IO;

public ActionResult Thumbnail()
{
    string imageFile = System.Web.HttpContext.Current.Server.MapPath("~/Content/tempimg/sti1.jpg");
    var srcImage = Image.FromFile(imageFile);
    var stream = new MemoryStream();
    srcImage.Save(stream , ImageFormat.Png);
    return File(stream.ToArray(), "image/png");
}
LatentDenis
  • 2,605
  • 10
  • 43
  • 91
Shyju
  • 206,216
  • 101
  • 402
  • 492
1

Simply try one of these depending on your situation (copied from here):

public ActionResult Image(string id)
{
    var dir = Server.MapPath("/Images");
    var path = Path.Combine(dir, id + ".jpg");
    return base.File(path, "image/jpeg");
}


[HttpGet]
public FileResult Show(int customerId, string imageName)
{
    var path = string.Concat(ConfigData.ImagesDirectory, customerId, @"\", imageName);
    return new FileStreamResult(new FileStream(path, FileMode.Open), "image/jpeg");
}
Community
  • 1
  • 1
naspinski
  • 33,200
  • 34
  • 107
  • 157