在ASP.NET MVC 3视图中呈现System.Drawing.Image的最佳方法

10

我有一个类型为 System.Drawing.Image 的对象,并希望在视图中显示该图像。最好的方法是什么?

我找到了一些自定义的 Html 帮助器方法可能适用于这种情况。还发现了一个示例,使用一个返回 FileContentResult 的新 action 方法来完成类似的操作。我想知道哪种技术最好、最容易实现。

编辑

更具体地说,我在控制器中有一个 System.Drawing.Image 变量中的图像,我想在视图中显示它。

1个回答

16
public ActionResult GetImg()
{
    string imageFile = System.Web.HttpContext.Current.
                                 Server.MapPath("~/Content/tempimg/unicorn.jpg");
    var srcImage = Image.FromFile(imageFile);
    using (var streak = new MemoryStream())
    {
      srcImage.Save(streak, ImageFormat.Png);
      return File(streak.ToArray(), "image/png");
    }     
}

现在您可以像这样在视图中调用它

<img src="@Url.Action("GetImg","YourControllerName")"  alt="alt text"/>

1
我在Controller中有一个System.Drawing.Image变量中的图像,我想在视图中显示它。如果可能的话,我希望避免保存到实际图像文件以显示图像。 - d456
变量名为src的类型是Drawing.Image。因此,请在我的答案中使用您的变量名(其中包含Image),而不是srcImage。 - Shyju

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接