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

Sni*_*fer 8 asp.net-mvc png

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

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

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

提前致谢

嗅探器

Dar*_*rov 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");
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后只需在视图中包含此图像:

<img src="<%= Url.Action("myimage", "home") %>" alt="my image" />
Run Code Online (Sandbox Code Playgroud)