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
  • 15,031
  • 23
  • 100
  • 187

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
  • 30,880
  • 8
  • 61
  • 118
4

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

Community
  • 1
  • 1
Nate
  • 30,286
  • 23
  • 113
  • 184
4

You can use FileContentResult like this:

byte[] imageData = GetImage(...); // or whatever
return File(imageData, "image/jpeg");
kprobst
  • 16,165
  • 5
  • 32
  • 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,839
  • 12
  • 48
  • 99
Shyju
  • 214,206
  • 104
  • 411
  • 497
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
  • 34,020
  • 36
  • 111
  • 167