How to load an image resource from a URL into a PHP script, using cURL?

13,779

Solution 1

What you need instead of imagecreatefrompng() is imagecreatefromstring(), because the former expects a filename instead of the file contents itself.

Solution 2

This worked for me

$image = imagecreatefromstring(file_get_contents('http://chart.googleapis.com/chart?cht=qr&chs=500x500&chl=xghsdfgsdfg&choe=UTF-8&chld=L|0'));
header('Content-Type: image/png');
imagepng($image);

Note: I had to use http rather than https because I haven't set up ssl on my local server.

Share:
13,779

Related videos on Youtube

Andrei Oniga
Author by

Andrei Oniga

Striving to become one of the best, one step at a time.

Updated on June 04, 2022

Comments

  • Andrei Oniga
    Andrei Oniga almost 2 years

    I'm using the Google Charts service to generate some QR codes that I afterward need to manipulate (e.g. rotate, scale) in a PHP script and merge with other images to generate one final image.

    How do I correctly load such a resource (from a URL) into a PHP script, in a way that will allow me to manipulate it?

    An example URL is: https://chart.googleapis.com/chart?cht=qr&chs=500x500&chl=xghsdfgsdfg&choe=UTF-8&chld=L|0

    I currently have the following code to retrieve the image using cURL:

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

    But when I use it like this:

    $image = imagecreatefrompng(getImage("https://chart.googleapis.com/chart?cht=qr&chs=500x500&chl=xghsdfgsdfg&choe=UTF-8&chld=L|0"));
    

    The following error is returned:

    Warning: imagecreatefrompng(‰PNG  ) [function.imagecreatefrompng]: failed to open stream: No such file or directory in /home/picselbc/public_html/projects/cakemyface/preview.php on line 383
    https://chart.googleapis.com/chart?cht=qr&chs=500x500&chl=xghsdfgsdfg&choe=UTF-8&chld=L|0
    
  • Andrei Oniga
    Andrei Oniga over 11 years
    You're right, that works! Any idea what I can do if I use the SimpleImage class though? (link). Because I'd need to use it like so: $image = new SimpleImage(getImage($url));.
  • Ja͢ck
    Ja͢ck over 11 years
    If SimpleImage needs a file you have to write one in a temporary location perhaps?
  • Andrei Oniga
    Andrei Oniga over 11 years
    I was afraid you would say that :)