MVC中的动态图像(Stack Exchange Beta站点)

时间:2010-07-11 18:40:50

标签: asp.net-mvc png

我一直在关注Stack Exchange Beta网站,并注意到每个进入测试版的网站都有一个顶部的图形,例如“Web Applications Beta”或“Gaming Beta”。

我想知道这些图像是单独创建的,还是以某种方式动态创建的?有没有办法使用MVC.NET动态创建PNG?

如果这个论坛的答案过于复杂,那么有人可以向我指出任何有用的文章吗?

提前致谢

嗅探者

2 个答案:

答案 0 :(得分:15)

是的,有一种方法可以使用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" />

答案 1 :(得分:1)

这对我有用。

makefile

使用它只是做与达林所说的相同的事情

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));
    }
}