2014-01-12 34 views
2

我正在尝试将一段文本更改为图像。我无法弄清楚我的代码有什么问题,以及如何使它透明。这是我到目前为止:PHP:将文本更改为具有透明度的PNG图像的功能

<?PHP 
function fsrep_imageaddress($address, $listingid) { 
    $font_size = 4; 
    $width = imagefontwidth($font_size)*strlen($address); 
    $height = imagefontheight($font_size); 
    $img = imagecreate($width,$height); 
    $bg = imagecolorallocate($img, 25, 25, 25); 
    $color = imagecolorallocate($img, 255, 255, 255); 
    $len = strlen($address); 
    $ypos = 0; 
    for($i=0;$i<$len;$i++){ 
     $xpos = $i * imagefontwidth($font_size); 
     imagechar($img, $font_size, $xpos, $ypos, $address, $color); 
     $address = substr($address, 1);  

    } 
    imagepng($img, ABSPATH.'wp-content/uploads/fsrep/houses/address-'.$listingid.'.png',100); 
    imagedestroy($img); 
} 

fsrep_imageaddress(Just Testing, 12) 
?> 
+1

什么是目前你的脚本做错了?你需要做的第一件事就是把'Just Testing'放在引号中,因为它是一个字符串而不是常量 –

回答

1

为什么它不起作用?

如果你看看错误日志,你会发现你需要在函数调用中将“Just Testing”放在引号中(谢谢@scrowler!)。然后你会得到一个错误,imagepng的质量等级为0(无压缩)为9(最大)。你有100!在这里,我将它设置为5(中等压缩)。

imagepng($img, ABSPATH.'wp-content/uploads/fsrep/houses/address-'.$listingid.'.png',5); 

如何设置透明背景?

调色板图像有一个奇怪的事情(即用imagecreate创建的那些)。分配的第一个颜色设置为背景,并且不能透明 - 所以您需要创建一个虚拟颜色,然后将其转换为透明。

// after this line 
$bg = imagecolorallocate($img, 25, 25, 25); 
// add this 
imagecolortransparent($img, $bg); 

结果

我做了这些改变,改变了文本为红色(255,0,0)的可读性和得到这个:

Result of code changes