How to adjust size of programatically created Bitmap to match text drawn on it?

Posted by TooFat on Stack Overflow See other posts from Stack Overflow or by TooFat
Published on 2010-05-07T01:17:42Z Indexed on 2010/05/07 1:28 UTC
Read the original article Hit count: 314

Filed under:
|
|

I have the following .ashx page that takes some query string parameters and returns a bitmap with the specified text written on it. The problem I have is that I am currently just manually setting the initial size of the bitmap at 100 X 100 when what I really want is to have the bitmap be just big enough to include all the text that was written to it. How can I do this?

  public void ProcessRequest (HttpContext context) {
    context.Response.ContentType = "image/png";
      string text = context.Request.QueryString["Text"];
    //set FontName
    string fontName;
    if (context.Request.QueryString["FontName"] != null)
    {
        fontName = context.Request.QueryString["FontName"];
    }
    else
    {
        fontName = "Arial";
    }
    //Set FontSize
    int fontEms;
    if (context.Request.QueryString["FontSize"] != null)
    {
        string fontSize = context.Request.QueryString["FontSize"];
        fontEms = Int32.Parse(fontSize);

    }
    else
    {
        fontEms = 12;
    }

    //Set Font Color
    System.Drawing.Color color;
    if (context.Request.QueryString["FontColor"] != null)
    {
        string fontColor = context.Request.QueryString["FontColor"];
        color = System.Drawing.ColorTranslator.FromHtml(fontColor);
        context.Response.Write(color.ToString());
    }
    else
    {
        color = System.Drawing.Color.Red;
    }
    using (System.Drawing.Text.PrivateFontCollection fnts = new System.Drawing.Text.PrivateFontCollection())
    using (System.Drawing.FontFamily fntfam = new System.Drawing.FontFamily(fontName))
    using (System.Drawing.SolidBrush brush = new System.Drawing.SolidBrush(color))
    using (System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(100, 100))
    {
        using (System.Drawing.Font fnt = new System.Drawing.Font(fntfam, fontEms))
        {
            fnts.AddFontFile(System.IO.Path.Combine(@"C:\Development\Fonts\", fontName));
            System.Drawing.Graphics graph = System.Drawing.Graphics.FromImage(bmp);
            graph.DrawString(text, fnt, brush, new System.Drawing.Point(0, 0));
            string imgPath = System.IO.Path.Combine(@"C:\Development\MyPath\Images\Text", System.IO.Path.GetRandomFileName());
            bmp.Save(imgPath);
            context.Response.WriteFile(imgPath);
        }
    }
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about ASP.NET