2010-07-11 34 views
7

我一直在尋找Stack Exchange Beta站點,並注意到進入beta版的每個站點都有一個圖形頂部的單詞「Web Applications Beta」或「Gaming Beta「例如。MVC中的動態圖像(Stack Exchange Beta站點)

我想知道,如果這些圖像是單獨創建或如果創建動態莫名其妙?有沒有使用MVC.NET在飛行中創建PNG的方法?

如果答案對於這個論壇來說太複雜了,任何人都可以指點我的任何文章嗎?

在此先感謝

嗅探器

回答

14

是有生成,並用ASP.NET MVC動態影像服務的方式。這裏有一個例子:

public class HomeController : Controller 
{ 
    public ActionResult MyImage() 
    { 
     // Load an existing image 
     using (var img = Image.FromFile(Server.MapPath("~/test.png"))) 
     using (var g = Graphics.FromImage(img)) 
     { 
      // Use the Graphics object to modify it 
      g.DrawLine(new Pen(Color.Red), new Point(0, 0), new Point(50, 50)); 
      g.DrawString("Hello World", 
       new Font(FontFamily.GenericSerif, 20), 
       new Pen(Color.Red, 2).Brush, 
       new PointF(10, 10) 
      ); 

      // Write the resulting image to the response stream 
      using (var stream = new MemoryStream()) 
      { 
       img.Save(stream, ImageFormat.Png); 
       return File(stream.ToArray(), "image/png"); 
      } 
     } 
    } 
} 

,然後只需在視圖中包括這一形象:

<img src="<%= Url.Action("myimage", "home") %>" alt="my image" /> 
+0

嗨達林 - 只是說我不是不理你。我只是沒有時間來測試你的代碼。只要我這樣做(並假設它有效),我會將其標記爲答案。謝謝你的時間。嗅探器 – Sniffer 2010-07-13 07:16:06

+0

我正在使用MVC 5,所顯示的代碼對我無效。我找到了解決問題的帖子[鏈接](http://pawelrychlicki.pl/Home/Details/43/mvc-return-image-dynamically-drawn-in-controller-mvc-3)。只需添加stream.Position = 0;在img.Save行之後。希望能幫助別人。 – user2789697 2014-10-19 13:11:46

0

這爲我工作。

using System.Web.Helpers; 
public class HomeController : Controller 
{ 
    public FileContentResult ImageOutput() 
    { 

     WebImage img = new WebImage("C:\\temp\\blank.jpg")); 

     //Do whatever you want with the image using the WebImage class 

     return new FileContentResult(img.GetBytes(), string.Format("image/{0}",img.ImageFormat)); 
    } 
} 

要使用它只是做同樣的事情,達林說

<img src="<%= Url.Action("ImageOutput", "home") %>" alt="my image" />