Voting

: min(seven, zero)?
(Example: nine)

The Note You're Voting On

heshan at sjtu dot edu dot cn
17 years ago
the imagettfbbox and imagettftext quirks are:

1. imagettfbbox and imagettftext have the same return value and both of them are wrong for angle not equal to zero.
2. imagettfbbox returns the correct bounding box when angle is zero.
3. the bounding box has a coordinate system that the x gets bigger from left to right and y gets bigger from top to bottom.
4. the "base point" used in imagettftext is the origin in the bounding box coordinate system.
5. when the angle is other than 0, it is actually rotated in the coordinate system with respect to the base point. so if we know the bounding box coordinate when angle is zero, we can get the new bounding box coordinate by doing the rotation by math equations manually.
6. to have pixel level accuracy, we should also be aware of another thing. suppose the axis is like this: |_|_|_|, the bounding box coordinate uses point on the vertical line while image function uses point on the horizontal line, so there is a 1 pixel difference you should take care of.

The following snippet creates minimal images containing a letter of different font and rotation angle. This is especially useful in captcha scripts.

<?php

function create_font_image( $size, $angle, $font, $char )
{
$rect = imagettfbbox( $size, 0, $font, $char );
if(
0 == $angle ) {
$imh = $rect[1] - $rect[7];
$imw = $rect[2] - $rect[0];
$bx = -1 - $rect[0];
$by = -1 - $rect[7];
} else {
$rad = deg2rad( $angle );
$sin = sin( $rad );
$cos = cos( $rad );
if(
$angle > 0 ) {
$tmp = $rect[6] * $cos + $rect[7] * $sin;
$bx = -1 - round( $tmp );
$imw = round( $rect[2] * $cos + $rect[3] * $sin - $tmp );
$tmp = $rect[5] * $cos - $rect[4] * $sin;
$by = -1 - round( $tmp );
$imh = round( $rect[1] * $cos - $rect[0] * $sin - $tmp );
} else {
$tmp = $rect[0] * $cos + $rect[1] * $sin;
$bx = -1 - round( $tmp );
$imw = round( $rect[4] * $cos + $rect[5] * $sin - $tmp );
$tmp = $rect[7] * $cos - $rect[6] * $sin;
$by = -1 - round( $tmp );
$imh = round( $rect[3] * $cos - $rect[2] * $sin - $tmp );
}
}
$im = imagecreatetruecolor( $imw, $imh );
imagefill( $im, 0, 0, imagecolorallocate( $im, 255, 0, 255 ) );
imagettftext( $im, $size, $angle, $bx, $by, imagecolorallocate( $im, 0, 0, 0 ), $font, $char );
imagegif( $im, trim( $font, './' ) . ord( $char ) . $angle . '.gif' );
imagedestroy( $im );
}

$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
$angles = array( -30, -20, -10, 0, 10, 20, 30 );
$fonts = array( './latinwide.ttf', './verdana.ttf', './times.ttf', './broadway.ttf' );
foreach(
$angles as $angle )
foreach(
$fonts as $font )
for(
$i = 0; $i < strlen( $chars ); ++$i )
create_font_image( 100, $angle, $font, $chars[$i] );
?>

<< Back to user notes page

To Top