Tuesday, July 9, 2013

ASP.NET - Render images dynamically with text overlay

This example shows how to render an image dynamically using aspx page with text overlay on top of it.


1) Create an aspx webform

2) Create a method as given below

public Bitmap OverlayText(Image oImage, string text)
        {
            Bitmap oBitmap = new Bitmap(oImage.Width, oImage.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            Graphics oGraphics = Graphics.FromImage(oBitmap);
            oGraphics.DrawImage(oImage, 0, 0);
            Font f = new Font(new FontFamily("Arial"), 20);
           
            SolidBrush oBrush = new SolidBrush(Color.FromArgb(255, System.Drawing.ColorTranslator.FromHtml("#000000")));

            RectangleF rect = new RectangleF(10, oImage.Height - 150, oImage.Width - 50, 100);
            StringFormat strFormat = StringFormat.GenericTypographic;

            oGraphics.DrawString(text, f, oBrush, rect, strFormat);

            oGraphics.Dispose();
            oBrush.Dispose();
            f.Dispose();

            return oBitmap;
        }



3) Call the method as given below in page_load by passing in the image object and overlay text. Make sure that you specify the virtual path of the image.

System.Drawing.Image img = System.Drawing.Image.FromFile(Server.MapPath("[SET PATH OF IMAGE HERE]"));
            Bitmap outputimage =OverlayText(img, overlaytext);

            using (MemoryStream ms = new MemoryStream())
            {
                outputimage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                ms.WriteTo(Response.OutputStream);
            }

            Response.ContentType = "image/png";
  

That's it. Run the app and you will see the text overlay on the image

1 comment:

Smartie said...

Thank you! I have found this extremely helpful :)