2010-08-15 63 views
0

我目前正在一个网站上工作,最近一直在使用GD与PHP自动创建透明图像,这些透明图像由网站上用于导航,标题等的文本组成。它为我节省了大量的时间在Photoshop中,我可以在需要时立即更改按钮上的文字。PHP GD从创建的PNG中修剪透明像素

好吧,我已经在这里遇到了死胡同。我找到了将“文本框”大小设置为我的图像的方法,以确定文本的大小。但我面临的问题是,我使用的TTF字体与GD期望的大小不同。基本上,最后一个字母将被切掉输出的图像。所以我想知道是否有办法解决这个问题,同时保持文本的紧密边缘,或使原始文本框的尺寸更大,然后“修剪”图像上的透明像素。

这是我与现在使用的代码...

<? 
$text = strip_tags($_GET['btn']); 
if(file_exists('nav_'.$text.'.png')) { 
    header("Content-type: image/png"); 

    $image = imagecreatefrompng('nav_'.$text.'.png'); 
    imagesavealpha($image, true); 
    imagealphablending($image, false); 
    imagepng($image); 
    imagedestroy($image); 
} else { 
    header("Content-type: image/png"); 

    $fontSize = 10; 
    $angle = 0; 
    $font = "RonniaBold.ttf"; 

    $size = imagettfbbox($fontSize, $angle, $font, $text); 
    $image = imagecreatetruecolor(abs($size[2]) + abs($size[0]) + 5, abs($size[7]) + abs($size[1]) + 5); 
    imagesavealpha($image, true); 
    imagealphablending($image, false); 

    $transparentColor = imagecolorallocatealpha($image, 200, 200, 200, 127); 
    imagefill($image, 0, 0, $transparentColor); 

    $textColor = imagecolorallocate($image, 125, 184, 222); 
    imagettftext($image, $fontSize, 0, 1, abs($size[5])+1, $textColor, $font, str_replace('_',' ',strtoupper($text))); 
    imagepng($image, 'nav_'.$text.'.png', 0); 
    imagedestroy($image); 
} 
?> 

希望你们有一些有识之士到这一点,我真的可以用它!

回答

2

只要有可能,我使用Imagick class,因为我更喜欢ImageMagick库。下面的例子几乎是逐字从here给出的例子。它创建基于所提供的文本尺寸的图像:

$text = 'Hello World!'; 

// Create a new ImageMagick objects. 
$im = new Imagick(); 
$draw = new ImagickDraw(); 
$colour = new ImagickPixel('#000000'); 
$background = new ImagickPixel('none'); 

// Set font properties. 
$draw->setFont('Fertigo_PRO.otf'); 
$draw->setFontSize(72); 
$draw->setFillColor($colour); 
$draw->setStrokeAntialias(true); 
$draw->setTextAntialias(true); 

// Get font metrics. 
$fm = $im->queryFontMetrics($draw, $text); 

// Create text. 
$draw->annotation(0, $fm['ascender'], $text); 

// Create a new empty canvas, using the text size. 
$im->newImage($fm['textWidth'], $fm['textHeight'], $background); 

// Create the image. 
$im->setImageFormat('png'); 
$im->drawImage($draw); 

// Save the image. 
$im->writeImage('test.png'); 

如果你想在Imagick类的详细信息,我建议从Mikko's Blog优秀Imagick articles

$size = imagettfbbox($fontSize, $angle, $font, $text); 

但是,当你写:要求与imagettfbox文本框的大小,当您使用$文本 -

+0

我认为Imagick对做不同的事情要好得多,但问题是我的主机没有安装在他们的服务器上,并且由于与另一个插件的冲突而无法安装。这就是为什么我试图用GD做到这一点。 – 2010-08-16 02:10:13

2

你必须与你的代码一个问题,阻止您确定您的文本的正确大小将文本添加到使用strtoupper($ text)的图像 - 这会使文字更大(除非使用等宽字体)。