出现问题,我的图片显示为错误。尝试了将字节数组转换为图像的两种方法。任何帮助表示赞赏。
查看:
if (product.ImageUploadBytes != null)
{
var base64 = Convert.ToBase64String(product.ImageUploadBytes);
var imgSrc = String.Format("data:image/gif;base64,{0}", base64);
<div class="panel-body"><img src=@imgSrc /></div>
<img src="@Url.Action("GetImage", "Products", new { id = product.ID })" />
}
控制器:
public ActionResult GetImage(int imageID)
{
Product p = new Product();
p = _context.Products.FirstOrDefault(x => x.ID == imageID);
if (p.ImageUploadBytes != null)
{
return File(p.ImageUploadBytes, "image/png");
}
else
{
return null;
}
}
数据库中的字节数组:Image
图像上传到DB:
[HttpPost]
public ActionResult AddImage(Product model, HttpPostedFileBase image)
{
if (image != null)
{
model.ImageUploadBytes = new byte[image.ContentLength];
image.InputStream.Read(model.ImageUploadBytes, 0, image.ContentLength);
}
_context.Products.Add(model);
_context.SaveChanges();
return View(model);
}