[英]How do I load an image from a database in ASP.NET MVC?
我已將圖像保存在數據庫中,並希望將其顯示給用戶。
圖像存儲的表如下所示:
Images
------
ImageData Byte
ImageName String
ContentType String
我應該怎么做才能加載並顯示在視圖中?
在圖像控制器類中:
public ActionResult ProfileImage(string userName)
{
var imageByteArray = // get image bytes from DB corresponding to userName
string contentType = // get image content type from DB for example "image/jpg"
string fileName = // get image file name from DB
return File(imageByteArray, contentType, fileName);
}
鑒於:
<img src='/Image/ProfileImage/yourUserName' alt='Profile image' />
您還需要在Global.asax中自定義路由:
routes.MapRoute(
"ProfileImage",
"Image/ProfileImage/{userName}",
new { controller = "Image", action = "ProfileImage", userName = "" }
);
您還可以將圖像加載到位圖中並應用更改大小,旋轉等。 如果這樣做,請考慮將圖像另存為png,因為GDI +(System.Drawing)可以使用這種格式保持最佳的質量和透明度。 緩存動態圖像也是一種好習慣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.