MVC how to serve images to response stream

StuTheDog picture StuTheDog · Jun 24, 2011 · Viewed 10.6k times · Source

In my controller I retrieve a list of products along with an image name, then scale the image down to the size needed by the view. The images are now in memory, ready to be written to the response stream. I know the client will send a response for each image but I have no idea how to hook into it to provide the image.

View code:

    @foreach (var product in Model.Products)
    {
       @product.Name
       <img src="@product.Thumbnail"/>
       Priced From [email protected]
    }

Controller:

    model.Products =
       DataContext.Products.Where(p => p.Category.Name
            .Equals(id)).Select(m => new ProductListItem
                {
                   Name = m.Name,
                   Thumbnail = ImageResizer.Resize(m.Image, 75, 100, <normally I put the output stream here>),
                   LowestPrice = SqlFunctions.StringConvert( m.PriceSet.Prices.Min(p =>p.Price1))
                }
    );

Where ImageResizer.Resize() signature is

Resize(string imageName, int width, int height, Stream outputStream)

So my question I think should be- what do I put in for the image name and how do I listen for requests for each image that can be written to the stream?

Answer

DanNsk picture DanNsk · Jun 25, 2011

Get Route/Action link on new action which downloads an image to set as image url,

<img src='@Url.RouteUrl("Full", new { action = "Image", controller = "Media", number = product.id })' />

or

<img src='@Url.Action("Image", new { number = 3 })' />

Add new action which has something like

public ActionResult Image(int? number)
{
    var media = mr.GetMedia(number);

    return base.File(media.Content, media.ContentType ?? "image/jpeg");
}

where media.Content is binary content or stream reference