在 Razor/MVC3 中顯示數據庫圖像(字節 [])?
我正在從我的 MS SQL 2008R2 數據庫返回一個數據集,其中包含一個數據表,我已經從我的 Razor 視圖中獲取數據。我添加了一個 byte[] 欄位,其中包含我試圖在該視圖上顯示的圖像縮略圖。
由於字節數組相對較小,我想我會嘗試內聯顯示字節數組。不過看了之後可能有一些瀏覽器相關的問題,我放棄了這個。
創建控制器方法似乎是可行的方法(兩種方法都可以在此處找到),但是我已經準備好字節數組以顯示在我的視圖中,並且不需要進行另一個 db 呼叫來根據 ID 獲取它。
這樣做,由於明顯的原因不起作用:
… 在頁面上顯示其他數據 ….
@if (Model.dsResults.Tables[0].Rows[i]["ImageBytes"] == null) { <img src="@Url.Content("~/Content/Images/NoPhoto.png")" border="0" /> } else { <img src="@Url.Action("GetImage", "SearchResults", new { imageBytes = Model.dsResults.Tables[0].Rows[i]["ImageBytes"] })" alt="Product Image" /> }…
控制器方法:
[Authorize] [AcceptVerbs(HttpVerbs.Get)] public ActionResult GetImage(byte[] imageBytes) { byte[] byteArray = imageBytes; return new FileContentResult(byteArray, "image/jpeg"); }…因為這本質上是試圖通過 http 發送字節數組。
所以,我的問題是,既然我的 Razor 視圖中已經有了字節數組,我該如何顯示它?
- 更新 -
我意識到不建議在視圖中進行處理,但由於數據已經存在,所以不能這樣做:
Response.Write((byte[])Model.dsResults.Tables[0].Rows[i]["ImageBytes"]);要麼…
Stream s = new MemoryStream(((byte[])Model.dsResults.Tables[0].Rows[i]["ImageBytes"])); System.Drawing.Image img = new System.Drawing.Bitmap(s);在其他文章中,我讀到你做了一個 Response.Write(byte[]…)) 但這在這種情況下不起作用。
- 你跌倒了 -
在我不斷尋求效率的過程中(不必向數據庫發出另一個請求),WebImage助手似乎是一個不錯的候選者。它的一個建構子將接受一個字節數組來初始化類,然後使用 .Write(“jpeg”) 方法,我可以看到圖像。
<td> @{ WebImage webImage = new WebImage(((byte[])Model.dsResults.Tables[0].Rows[i]["ImageBytes"])); webImage.Write("jpeg"); } </td>使用 WebImage.Write() 的問題在於,一旦使用,圖像是唯一呈現在頁面上的東西。有沒有辦法將它直接呈現給 Razor 視圖頁面上的“控制項”?
- 更新 -
這繼續困擾著我……所以我嘗試了以下方法,我認為這可能有效,因為這是我們從行動中所做的……
if (Model.dsResults.Tables[0].Rows[i]["ImageBytes"] != DBNull.Value) { var img1 = new FileContentResult(((byte[])Model.dsResults.Tables[0].Rows[i]["ImageBytes"]), "image/jpeg"); <text> <img src="@new FileContentResult(((byte[])Model.dsResults.Tables[0].Rows[i]["ImageBytes"]), "image/jpeg")" /> </text> }……不起作用。
最終,我選擇了兩條路線。非常低效,因為圖像字節已經準備好進入視圖。應該有一個網路助手圖像控制項,它將直接從圖像的字節數組(或圖像類型)呈現圖像。也許有,我錯過了。
要獲取字節(是的,從頭再來):
[AcceptVerbs(HttpVerbs.Get)] public ActionResult GetThumbnailImage(string itemListID) { byte[] imageBytes = null; client = new FeederServiceClient(); imageBytes = client.GetItemThumbnail( itemListID ); if (imageBytes == null) { return new FilePathResult("~/Content/Images/NoPhoto.png", "image/png"); } else { return new FileContentResult(imageBytes, "image/jpeg"); } }然後顯示圖像:
<img src="@Url.Content("~/Thumbnails/" + @Model.dsResults.Tables[0].Rows[i]["ItemListID"] )" />在 Global.asax 中放置以下路由:
routes.MapRoute(name: "Thumbnails", url: "Thumbnails/{itemListID}", defaults: new { controller = "Results", action = "GetThumbnailImage" });
Model.Content 是一個 byte[] 圖像。
@{ string imageBase64 = Convert.ToBase64String(Model.Content); string imageSrc = string.Format("data:image/gif;base64,{0}", imageBase64); }像這樣使用:
<img src="@imageSrc" alt="@Model.Name" width="100" height="100" />