Calculating string length for use in image

Discussion in 'PHP' started by Cobnut, Feb 29, 2008.

  1. #1
    I'm building a simple graphing function and would like to include some labels within the bars of the graph; like this:

    [​IMG]

    I've got tests for the width of the bars that increases/decreases the font number (or doesn't show text at all) but I need some way to limit the length of the text dependent upon the size of the bar itself. Ideally, I'd like to be able to say 'if the text gets within x pixels of the top of the bar, then substr it down to a point where it's within the bar'. As it happens, for this particular project I can be fairly certain that the bars are always going to be around 75% of the chart but I can't control the label text itself and some could be longer than those shown on the example.

    I suppose what I'm after is some direct equation between the standard font number in imagestring and the 'size' per character.

    Anyone have any ideas?

    Jon
     
    Cobnut, Feb 29, 2008 IP
  2. RoscoeT

    RoscoeT Peon

    Messages:
    78
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #2
    I think you should likely do this with CSS rather than in your php code. Font size and pixel size vary from machine to machine.
     
    RoscoeT, Mar 1, 2008 IP
  3. stoli

    stoli Peon

    Messages:
    69
    Likes Received:
    14
    Best Answers:
    0
    Trophy Points:
    0
    #3
    The imagefontwidth function should give you what you want:
    http://www.php.net/manual/en/function.imagefontwidth.php

    Here is a way you could use it to truncate a string to fit in a given image:
    <?php
    
    $text = "Pack my box with five dozen liquor jugs";
    $font = 3; // font size
    $outputimage = 1; // 1 to output image, 0 to output text
    
    // create a 140*30 image
    $imgwidth = 140;
    $imgheight = 30;
    $im = imagecreate($imgwidth, $imgheight);
    
    // blue background and white text
    $bg = imagecolorallocate($im, 0, 0, 255);
    $textcolor = imagecolorallocate($im, 255, 255, 255);
    
    // limit font range
    if ($font < 0 || $font > 5) $font = 0;
    
    // truncate the text to fit the image width 
    $width = strlen($text) * imagefontwidth($font);
    while ($width > $imgwidth) {
      $text = substr($text, 0, -1);
      $width = strlen($text) * imagefontwidth($font);
    }
    
    // write the string at the top left of image
    imagestring($im, $font, 0, 0, $text, $textcolor);
    
    // output the image
    if ($outputimage) {
      header("Content-type: image/png");
      imagepng($im);
    } else {
      echo $text;
    }
    
    ?>
    PHP:
    Try it with different font sizes, either outputting the text or image to see how it works.
     
    stoli, Mar 1, 2008 IP