我正在使用 EF 4.1 Code First,为了简单起见,假设我有以下实体类:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public Byte[] Image { get; set; }
}
我已经成功创建了一个工作创建 View ,允许将 Person 对象添加到数据库中。
但是当我要显示一个人的详细信息时,我陷入了显示图像的困境。经过一些研究,我有以下几点:
// To convert the Byte Array to the author Image
public FileContentResult getImg(int id)
{
byte[] byteArray = DbContext.Persons.Find(id).Image;
return byteArray != null
? new FileContentResult(byteArray, "image/jpeg")
: null;
}
在我尝试列出人员详细信息的 View 中,我有以下内容来显示图像:
<img src="@Html.Action("getImg", "Person", new { id = item.Id })" alt="Person Image" />
但是上述方法不起作用,我的图像源[src]属性返回空。
最佳答案
如果您已经在模型中加载了图像,还有一种更简单的方法:
<img src="data:image;base64,@System.Convert.ToBase64String(Model.Image)" />
通过这种方式,您不需要再次访问服务器来从数据库中获取图像 byte[]
。
关于arrays - 将字节数组转换为图像并在 Razor View 中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7560830/