James Cadd
James Cadd

Reputation: 12216

What's a good way to dynamically generate PNGs in ASP.NET?

I have a need to generate small PNG images in ASP.NET. The images could have things like simple geometries and text. Is it necessary to use a 3rd party library to generate images in ASP.NET?

Upvotes: 2

Views: 2252

Answers (2)

BrokenGlass
BrokenGlass

Reputation: 160852

You can do that just using the Bitmap and other graphics related classes in the .NET framework.

        Bitmap bmpImage = new Bitmap(width, height);
        Graphics gr = Graphics.FromImage(bmpImage);
        //Draw using gr here

        //stream to the client
        Response.ContentType = "image/png";

        //write to memory stream first, png can only be written to seekable stream
        using(MemoryStream memStream = new MemoryStream())
        {
          bmpImage.Save(memStream, ImageFormat.Png);
          memStream.WriteTo(Response.OutputStream);
        }
        bmpImage.Dispose();

Upvotes: 5

kprobst
kprobst

Reputation: 16651

Something like this?

Bitmap bmp = new Bitmap(300, 300);
Graphics g = Graphics.FromImage(bmp);

g.Clear(Color.Transparent);
g.FillRectangle(Brushes.Red, 100, 100, 100, 100);

g.Flush();
bmp.Save("test.png", System.Drawing.Imaging.ImageFormat.Png);

(from here)

You'd have to play around with the contents of the image of course, but the graphics namespace probably has most of what you need.

Upvotes: 7

Related Questions