doulu1020 2012-11-24 09:47
浏览 102
已采纳

使用PHP GD`imagecreatefromstring`函数创建图像的问题

I have a simple service that generates a PNG image of any text, using the parameters passed via a URL. One of the parameters is the text itself, the rest are things like 'font', 'color', 'font weight' etc.

An example of such a URL is: http://picselbocs.com/projects/cakemyface/text.php?params=Verdana%7C18%7Cbold%7Cnormal%7Ccenter%7C%23cc0000%7Cunderline&text=Hello%20world!

which generates the following PNG:

original

In another script, I'm using cURL to retrieve such a resource generated by this service, which I then convert to an image using imagecreatefromstring(), because I need to operate on it - things like rotating and scaling -, then to merge it with some other images. For this I use the following code:

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

This same code is available here, where you can see the output. The problem is that the code above outputs some strange PNG, where all the letters are filled rectangles, like in the example bellow:

sample result

Why does this happen and how can I solve it?

One other curious thing is that if I replace a URL to a text-image with, for instance, a link to a QR code generated with the Google Charts tool (e.g. QR code), the result is what it's supposed to be...

  • 写回答

1条回答 默认 最新

  • dongpinken0498 2012-11-24 10:09
    关注

    After a little playing about I discovered the issue and the solution!

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

    The way I create my image is just a quick way without using curl, it seems the image needs it's alpha channels saving.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器