Simple Machines Community Forum

General Community => Scripting Help => Topic started by: Windy on October 27, 2006, 10:47:48 AM

Title: get the width of a string in pixels? (php)
Post by: Windy on October 27, 2006, 10:47:48 AM
^title
Title: Re: get the width of a string in pixels? (php)
Post by: Daniel15 on October 27, 2006, 11:04:05 AM
You can do this using the GD library, but it requires you to have the font available as a .TTF file:


<?php

function fixbbox($bbox) {
   
$xcorr=0-$bbox[6]; //northwest X
   
$ycorr=0-$bbox[7]; //northwest Y
   
$tmp_bbox['left']=$bbox[6]+$xcorr;
   
$tmp_bbox['top']=$bbox[7]+$ycorr;
   
$tmp_bbox['width']=$bbox[2]+$xcorr;
   
$tmp_bbox['height']=$bbox[3]+$ycorr;
   
   return 
$tmp_bbox;
}

$font 'arial.ttf';
$fontSize 9.5;
$text 'Test 123';

$bbox fixbbox(imagettfbbox($fontSize0$font$text));
echo 
'The text is '$bbox['width'], ' pixels wide';
?>


[/i](don't ask about the fixbbox function, I don't know how it works, as I didn't write it. I just got it from the PHP website, under the user comments)[/i]

Replace arial.ttf with the name of the font, 9.5 with the font size and Test 123 with the text. On my computer, this shows output like:
QuoteThe text is 46 pixels wide

:D
Title: Re: get the width of a string in pixels? (php)
Post by: Windy on October 28, 2006, 01:32:04 AM
thanks :D