2014-01-12 50 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