2012-11-24 54 views
2

我有一個簡單的服務,它使用通過URL傳遞的參數生成任何文本的PNG圖像。其中一個參數是文字本身外,其餘均之類的東西「字體」,「顏色」,「字體粗細」等使用PHP GD創建映像的問題`imagecreatefromstring`函數

這樣的URL的一個例子是: http://picselbocs.com/projects/cakemyface/text.php?params=Verdana%7C18%7Cbold%7Cnormal%7Ccenter%7C%23cc0000%7Cunderline&text=Hello%20world!

產生以下PNG:

original

在另一個腳本中,我使用捲曲來獲取該服務,然後我轉換爲使用imagecreatefromstring()的形象,因爲我需要在其上運行產生這樣的資源 - 比如旋轉和縮放 - 然後合併它與其他一些圖像。 爲此,我使用下面的代碼:

function getImage($url){ 
      $ch = curl_init ($url); 
      curl_setopt($ch, CURLOPT_HEADER, 0); 
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
      curl_setopt($ch, CURLOPT_BINARYTRANSFER,1); 
      $resource = curl_exec($ch); 
      curl_close ($ch); 

      return $resource; 
    } 


    $url = "http://picselbocs.com/projects/cakemyface/text.php?params=Verdana%7C18%7Cbold%7Cnormal%7Ccenter%7C%23cc0000%7Cunderline&text=Hello%20world!"; 

    $string = getImage($url); 
    $image = imagecreatefromstring($string); 

    // Send the image to the client 
    header("Content-type: image/png"); 
    header("Content-disposition: inline; filename=mytext.png"); 
    imagepng($image); 
    imagedestroy($image); 

此相同的代碼可here,在這裏你可以看到輸出。 的問題是,上面的代碼輸出一些奇怪的PNG,其中所有的字母都在波紋管的例子填充矩形,如:

sample result

爲什麼會出現這種情況,我該如何解決呢?

另外一個奇怪的是,如果我替換URL到文本圖像,例如,與谷歌圖表工具(如QR code)生成的QR代碼的鏈接,結果是什麼它應該是...

+1

當我按照示例網址(第一個),它只是一個10x10px的白色圖像? – Dale

+0

我更正了鏈接,請重試。 –

+2

可能是透明度問題?嘗試在text.php – gogowitsch

回答

3

稍微玩了一下我發現了問題和解決方案!

$image = imagecreatefromstring(file_get_contents('http://picselbocs.com/projects/cakemyface/text.php?params=Verdana|18|bold|normal|center|%23cc0000|underline&text=Hello%20world!')); 
imagesavealpha($image, TRUE); // this is the fix 
header("Content-Type: image/png"); 
imagepng($image); 

我創建圖像的方式只是一種不使用捲曲的快速方式,看起來圖像需要它的alpha通道保存。

+0

這就是訣竅!太棒了!非常感謝! –

+0

老闆:)沒問題:) – Dale