How to Create Dynamic Font-Based Images with PHP

  1. Home
  2. Knowledge Base
  3. WordPress Plugins
  4. How to Create Dynamic Font-Based Images with PHP

We wanted to create stylish text images for our page and post headings, but we didnt want to create them in advance, we wanted them on the fly. This is a tutorial on how we accomplished this using PHP.

Youll need PHP (PHP: Hypertext Preprocessor) the open source dynamic language the code in our example is written. We wont elaborate, the internet is full of information reguarding PHP.

Youll need the GD library, an open source code library for the dynamic creation of images by programmers, typically installed along with PHP.Information on the GD library also abounds on the internet. Check with your host if you are unsure if you have it installed.

A windows font of your choice, for our site we chose a nice font called Agency. Upload a copy of this font onto your server wherever you like, just be sure to change the path/to/the/font to your fonts path in the PHP code.

Determine the colors of your image (in hexidecimal form) for the following: text, background & text-shadow (if wanted). Hexadecimal uses three sets of numbers to represent the Red, Green, and Blue values for a particular color. We chose a blue text, with a white background and a light grey shadow. There are quite a few free color picking programs and websites available, we use ColorPic by iconico.com for all our color needs. Its freeware and does not include any other unwanted software included in the download package.

Save this PHP code and name the file font.php:

Simply call the dynamic font based image in a generic HTML image tag. Be sure to use the alt portion of the image tag so that if the image generation fails text still appears, not to mention this will aid in SEO.

 

How do we dynamically use this technique in conjunction with our sites code? The text for our images come from the <?php the_title(); ?> call from WordPress. Hence, whatever text is set for the page or post title will be displayed in image form. No need to create static text images for our pages and posts.

Room for improvement? Why yes there is always improvements that can be made to the code, some or our thoughts include:

  • Create an on the fly HEX color conversion based on the $color and $bgcolor variables
  • Determine the top offset based on the image height and the font size, allowing all text to align in the center of the image.
  • Auto width based on number of text characters. This could be tricky and may require a monospacing (fixed-width) font.

Was this article helpful?

Related Articles

Leave a Reply