来自字节数组的ASP.NET MVC图像

目前我的ViewModel中有一个代表我的Image的字节数组。 我用以下代码显示它:

 

现在我不希望在源文件中有一个Base64字符串,而是一个指向图像的链接。 喜欢:

  

这将返回一个图像。

如何编写这样的方法来返回Image链接?

您可以定义将为图像提供服务的控制器操作:

 public class ImagesController: Controller { public ActionResult Index(int id) { byte[] imageData = ... go get your image data from the id return File(imageData, "image/png"); // Might need to adjust the content type based on your actual image type } } 

在您的视图中,只需将img标记的src属性指向此控制器操作:

  

一种方法是将其添加到新的c#类或HtmlExtensionsclass中

 public static class HtmlExtensions { public static MvcHtmlString Image(this HtmlHelper html, byte[] image) { var img = String.Format("data:image/jpg;base64,{0}", Convert.ToBase64String(image)); return new MvcHtmlString(""); } } 

然后你可以在任何视图中执行此操作

 @Html.Image(Model.MyImageBytes)