问题
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 $@product.LowestPrice
}
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?
回答1:
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
回答2:
Ok finally figured it out thanks to DanNsk and this post here
public FileResult Image(string id)
{
var dir = Server.MapPath("/content/images");
var path = Path.Combine(dir, id);
var stream = XTC.Helpers.ImageResizer.Resize( path, 150, 200);
var result = new FileStreamResult(stream, "image/jpeg");
return result;
}
来源:https://stackoverflow.com/questions/6473811/mvc-how-to-serve-images-to-response-stream