使用 ASP.NET MVC5 我知道我可以像这样简单地从 Controller 加载图像标签的源:
<img class="img-thumbnail" src="@Url.Action("GetImage", "Product", new { Model.ProductId })" />
随着 Controller 返回 FileContentResult
public FileContentResult GetImage(int productId) {
Product prod = repository.Products
.FirstOrDefault(p => p.ProductID == productId);
if (prod != null) {
// ImageData is the byte array
return File(prod.ImageData, prod.ImageMimeType);
} else {
return null;
}
}
但是,我的 View 需要将图像加载为 div 的 CSS 背景:
<div class="mdl-card__media mdl-color-text--grey-50" style="padding-left: 10px; height:274px; background: url('@Model.ImagePath;')">
ImagePath 值未正确保存,使用绝对路径 E:\Development\ortund\blog\blog\Content\Images\uploads\{filename}
然而,字节数组被正确保存。
我可以使用 @Url.Action()
方法将图像的字节数组加载到 css 中并以这种方式呈现图像吗?
如果不行,怎么办?
最佳答案
@Url.Action()
不是执行此操作的方法。
相反,我将数据库中的图像字节数组转换为 base64 字符串,然后将其用于背景:
<div style="background: url(data:@Model.ImageMimeType;base64,@Convert.ToBase64String(Model.Image) )"></div>
关于c# - 如何从保存在数据库中的字节数组设置CSS背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43065395/