locked
Drawing text to a image? In the least amount of code RRS feed

  • Question

  • User199372478 posted

    Im trying to draw text to an image in asp.net c#

    if possible i want to have the image created with the toolbox image tool,

    and then dynamically create the text on it.

    Can anyone point me in the general direction? I have looked on google and this forum and none of the methods worked for me

    Thanks!

    Tuesday, November 8, 2011 10:52 AM

All replies

  • User88100680 posted

    Yes you can generate dynamic image. I have craeted very basic code, you can enhance as you like. I created generic handler called "RenderText.ashx" and below is the code for it. And you can use example url like "RenderText.ashx?h=100&w=100&t=hello world&f=Tahoma&s=12". Let me know further.

    <%@ WebHandler Language="C#" Class="RenderText" %>
    
    using System;
    using System.Web;
    using System.Drawing;
    
    public class RenderText : IHttpHandler {
        
        public void ProcessRequest (HttpContext context) {
            context.Response.ContentType = "image/jpg";
    
            var height = int.Parse(context.Request["h"]);
            var width = int.Parse(context.Request["w"]);
            var text = context.Request["t"];
            var font = context.Request["f"];
            var size = int.Parse(context.Request["s"]);//px
    
            var bmp = new Bitmap(width, height);
            var g = Graphics.FromImage(bmp);
    
            g.FillRectangle(Brushes.White, 0, 0, width, height);
            g.DrawString(text, new Font(font, size, FontStyle.Regular, GraphicsUnit.Pixel), Brushes.Black, new Point(0, 0));
    
            bmp.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
     
        public bool IsReusable {
            get {
                return false;
            }
        }
    }
    Wednesday, November 16, 2011 7:45 AM