代码之家  ›  专栏  ›  技术社区  ›  Sniffer

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

  •  8
  • Sniffer  · 技术社区  · 16 年前

    我在查看Stack Exchange测试版网站时注意到,每个进入测试版的网站顶部都有一个图形,例如“Web应用程序测试版”或“游戏测试版”。

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

    如果答案对这个论坛来说太复杂了,有人能给我指出一些有帮助的文章吗?

    提前谢谢

    嗅探器

    2 回复  |  直到 16 年前
        1
  •  15
  •   Darin Dimitrov    16 年前

    是的,有一种使用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" />
    
        2
  •  1
  •   Ray Cheung    10 年前

    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" />