Ever had the situation where you have a piece of string which you need to overlay on an image? Maybe a situation where the area reserved for the string is known in pixels but you need to know the font size to fill most of the area? Think no more!

Here is a small example of how to fit a certain piece of a string on to an area of which you know the width and the height or only the width. The magic happens through the ImageMagick CAPTION: format. You can see from the example images how the parameters actually affect the image.

  1. <?php
  2.  
  3. /* How wide is our image */
  4. $image_width = 200;
  5.  
  6. /* Give zero for autocalculating the height */
  7. $image_height = 200;
  8.  
  9. /* Specify the text */
  10. $text = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
  11.         Mauris lectus mi, mattis non, euismod vel, sagittis nec, ipsum.";
  12.  
  13. /* Instanciate imagick */
  14. $im = new Imagick();
  15.  
  16. /* Create new image using caption: pseudo format */
  17. $im->newPseudoImage( $image_width, $image_height, "caption:" . $text );
  18.  
  19. /* Put 1px border around the image */
  20. $im->borderImage( 'black', 1, 1 );
  21.  
  22. /* PNG format */
  23. $im->setImageFormat( "png") ;
  24.  
  25. /* Output */
  26. header( "Content-Type: image/png" );
  27. echo $im;
  28.  
  29. ?>

Here is image with width 100 and height 0:

width_100_height_0.png

Width 100 Height 50:

width_100_height_50.png

Width 200 Height 200 (as you can see the font size is now larger):

width_200_height_200.png