无法在MVC 5中将byte []渲染为图像ASP.Net

时间:2017-12-07 17:34:13

标签: c# asp.net-mvc

我有一个使用Northwind数据库的简单MVC 5应用程序。有问题的视图显示了Northwind中Categories表的类别列表。我试图使用img tag渲染字节数组,但没有成功。

我查看了MVC How to display a byte array image from model并尝试使用自定义的html助手,但即使这样也无效

在将byte []转换为图像时,我的方法中是否存在某些缺失?

尝试以下(查看我试过的img标签)

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.CategoryName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Description)
        </td>
        <td>
            <img src="@String.Format("data:image/jpg;base64,{0}", Convert.ToBase64String(item.Picture))" />
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.CategoryID }) |
            @Html.ActionLink("Details", "Details", new { id=item.CategoryID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.CategoryID })
        </td>
    </tr>
}

EF类别

public partial class Category
{
    public int CategoryID { get; set; }

    [Required]
    [StringLength(15)]
    public string CategoryName { get; set; }

    [Column(TypeName = "ntext")]
    public string Description { get; set; }

    [Column(TypeName = "image")]
    public byte[] Picture { get; set; }
}

行动方法

  public class CategoriesController : Controller
  {
        private NorthwindDB db = new NorthwindDB();

        // GET: Categories
        public ActionResult Index()
        {
            return View(db.Categories.ToList());
        }
  }

1 个答案:

答案 0 :(得分:1)

我发现转换Nortwind图像格式化base64字符串并不容易。我找到了source。根据解释,&#34; Northwind图像是使用Microsoft Access创建的,因此它们具有78字节的OLE标头&#34; 。所以,我们应该删除标题。首先,修改Category实体。

public partial class Category
{
    public int CategoryID { get; set; }

    [Required]
    [StringLength(15)]
    public string CategoryName { get; set; }

    [Column(TypeName = "ntext")]
    public string Description { get; set; }

    [Column(TypeName = "image")]
    public byte[] Picture { get; set; }

    [NotMapped]
    public string Base64String
    {
        get
        {
            var base64Str = string.Empty;
            using (var ms = new MemoryStream())
            {
                int offset = 78;
                ms.Write(Picture, offset, Picture.Length - offset);
                var bmp = new System.Drawing.Bitmap(ms);
                using (var jpegms = new MemoryStream())
                {
                    bmp.Save(jpegms, System.Drawing.Imaging.ImageFormat.Jpeg);
                    base64Str = Convert.ToBase64String(jpegms.ToArray());
                }
            }
            return base64Str;
        }
    }
}

然后将Base64String属性放在img属性中。

<img src="@String.Format("data:image/jpg;base64,{0}", item.Base64String)" />