Search code examples
c#fontsgdi+embedded-fonts

Use GDI+ with C# to create an image for a site


I'd like to use GDI to generate text images with my fonts on a server to be served on my site.

I want to use any font on my sites, but of course couldn't use any font on a web site... so I guess I'd need to generate images of the text myself.

Ideas how to accomplish this?

Thanks.


Solution

  • private void button1_Click( object sender, EventArgs e )
    {
        using( Font f = new Font( "Times New Roman", 22f ) )
        {
            pictureBox1.Image = CreateImage( "TEXT", pictureBox1.Size, f, Color.Black );
        }
    }
    
    Bitmap CreateImage( string text, Size imageSize, Font font, Color fontColor )
    {
        Bitmap image = new Bitmap( imageSize.Width, imageSize.Height );
        using( Graphics g = Graphics.FromImage( image ) )
        using( Brush brush = new SolidBrush( fontColor ) )
        {
            g.DrawString( text, font, brush, new PointF( 0, 0 ) );
        }
    
        return image;
    }
    

    That will simply create an image with some text of a certain size and assign it to a picturebox. You would of course need to add functionality for setting alignment and things of that nature, but this is the basic idea. Create an image, get a Graphics object from it, and draw a string.

    You can also obtain the width and height of a drawn string using some font 'f' by using the Graphics.MeasureString method.