簡體   English   中英

使用 PHP GD `imagecreatefromstring` 函數創建圖像的問題

[英]Issue with creating an image with PHP GD `imagecreatefromstring` function

我有一個簡單的服務,它使用通過 URL 傳遞的參數生成任何文本的 PNG 圖像。 參數之一是文本本身,其余參數是“字體”、“顏色”、“字體粗細”等。

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

生成以下PNG:

原來的

在另一個腳本中,我使用 cURL 來檢索此服務生成的此類資源,然后我使用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);

此處提供相同的代碼,您可以其中查看輸出。 問題是上面的代碼輸出了一些奇怪的 PNG,其中所有字母都是填充的矩形,如下例所示:

樣本結果

為什么會發生這種情況,我該如何解決?

另一件奇怪的事情是,如果我將文本圖像的 URL 替換為,例如,使用 Google Charts 工具生成的 QR 碼的鏈接(例如QR 碼),結果就是它應該是......

經過一番玩耍后,我發現了問題和解決方案!

$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);

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM