Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Images in MVC (Stack Exchange Beta sites)

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

like image 977
Sniffer Avatar asked Jul 11 '10 18:07

Sniffer


2 Answers

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" />
like image 75
Darin Dimitrov Avatar answered Jan 02 '23 16:01

Darin Dimitrov


This worked for me.

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

To use it just do the same thing as Darin said

<img src="<%= Url.Action("ImageOutput", "home") %>" alt="my image" />
like image 32
Ray Cheung Avatar answered Jan 02 '23 15:01

Ray Cheung