views:

28

answers:

1

Hi

I've been looking at the Stack Exchange Beta sites and noticed that each site that goes into beta has a graphic at the top with the words 'Web Applications Beta' or 'Gaming Beta' for example.

I wondered if these images are individually created or if the are created dynamically somehow? Is there a way using MVC.NET to create PNGs on the fly?

If the answer is too complicated for this forum, can anybody point me to any articles that will help?

Thanks in advance

Sniffer

+1  A: 

Yes there is a way to generate and serve images dynamically with ASP.NET MVC. Here's an example:

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

And then simply include this image in the view:

<img src="<%= Url.Action("myimage", "home") %>" alt="my image" />
Darin Dimitrov
Hi Darin - just to say I'm not ignoring you. I just haven't had time to test your code out yet. As soon as I do (and presuming it works ) I'll mark it down as the answer. Thanks for your time. Sniffer
Sniffer