Search code examples
asp.netihttphandler

How not to be limited by image size using an Image Handler


I am converting text to image. Some of the text is longer in length than others.
How do I make sure that none of the text is truncated?

The code below is limiting my bitmap to 250, 30.

System.Drawing.Bitmap imgIn = new System.Drawing.Bitmap(250, 30);
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(imgIn);
g.Clear(System.Drawing.Color.White);
    System.Drawing.Font font = new System.Drawing.Font("Arial", 10, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);

I was following this example:How to convert Email Address or another text form TextBox to image

UPDATE

I found this article that helped accomplish my task: Generate Image from text using C# OR Convert Text in to Image using C#

After I was able to resize the image according to the text length, I discovered that I need to introduce line breaks in the text otherwise the image was going all the way to Timbuktu when the text was a couple of sentences.
How do I introduce line breaks in long texts?


Solution

  • You can use TextRenderer.MeasureText to get the size in pixels of the text.

    Size size = TextRenderer.MeasureText("text", Font("Arial",10));
    System.Drawing.Bitmap imgIn = new System.Drawing.Bitmap(size.Width, size.Height);
    

    EDIT

    I found this article on how to write an HTTP Handler that will do what you want, it even wraps text to fit.