1
我已經在數據庫上保存了一個圖像,並且想要將其顯示給用戶。如何在ASP.NET MVC中從數據庫加載圖像?
表的圖像存儲在看起來像這樣:
Images
------
ImageData Byte
ImageName String
ContentType String
我應該怎麼做來加載,並顯示在我的觀?
我已經在數據庫上保存了一個圖像,並且想要將其顯示給用戶。如何在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)可以保持這種格式的最佳質量和透明度。緩存動態圖像也是一個很好的做法。
ImageData = Convert.ToByte [](reader [「@ ImageData」]); 如何讀取字節類型的信息?我在第一個「]」後出錯了。 – 2010-08-25 15:26:15
它是什麼意思15? imageName? – 2010-08-25 15:35:38
對不起,它應該是用戶名(或者如果你這樣決定的話,圖像名稱) – 2010-08-25 18:56:27