Reputation: 15886
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.
Upvotes: 16
Views: 22229
Reputation: 218722
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");
}
Upvotes: 2
Reputation: 16651
You can use FileContentResult
like this:
byte[] imageData = GetImage(...); // or whatever
return File(imageData, "image/jpeg");
Upvotes: 4
Reputation: 31250
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
.
Upvotes: 20
Reputation: 34689
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");
}
Upvotes: 1