2009-09-11 75 views
6

我是新來的asp.net mvc,但我想用GDI +做一個有趣的應用程序,我需要用asp.net mvc做一些圖像視圖。ASP.Net MVC如何在視圖中顯示模型的圖像屬性?

我有具有圖像屬性的Model:

namespace DomainModel.Entities 
{ 
    public class BackgroundImage 
    { 
     // Properties 
     public Image Image {get; private set; } 

     public BackgroundImage() 
     { 
      Image = Image.FromFile(@"D:\ProjectZero\DomainModel\image\bkg.PNG"); 

     } 
    } 
} 

控制器發送到以下的視圖:

public ActionResult Index() 
     { 

      BackgroundImage bkImg = new BackgroundImage(); 
      return View(bkImg); 
     } 

視圖看起來像這樣:

<p> Height: </p><%= Model.Image.Height //it prints the height of the image %> </br> 
<p> Width: </p><%= Model.Image.Width //it prints the width %> </br> 
<p> Image: </p><%= Model.Image //does not work to display the image %> 

我如何顯示該圖像屬性?

我需要一個div的背景圖片。我不需要調整圖像大小,我只需要以正常大小顯示它。

是否有我錯過的Html Helper?

謝謝,你的時間!

回答

15

你需要寫一個控制器動作,將寫入圖像到響應流,並設置適當的內容類型說「圖像/ PNG」。然後你可以使用img標籤在視圖中引用這個動作:

public ActionResult Image() 
{ 
    byte[] image = GenerateImage(); 
    return File(image, "image/png"); 
} 

而且你的視圖中:

<img src="<%= Url.Action("Image") %>" alt="" /> 
+1

這解決了我的問題,但我需要使用這樣的: 公共字節[ ] ImageToByteArray(System.Drawing.Image imageIn) { MemoryStream ms = new MemoryStream(); imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif); return ms.ToArray(); } 用於將我的圖像轉換爲字節數組。 – andreiursan 2009-09-11 08:58:56

+1

我一直在試圖做這個爲期2天,並已被引導下來的HttpHelpers路徑,派生的ActionResults調用ImageResults並沒有得到我的地方,這個解決方案第一次工作,非常好! – 2012-04-15 22:05:09

+0

以上視圖代碼示例中缺少At符號。 kroiz 2013-08-05 12:46:41