How to create PHP image object from downloaded image?

1.8k views Asked by At

So I've been using this approach to resize images uploaded via forms in PHP:

list ($width, $height, $type, $w)=getimagesize($_FILES[$imageName]['tmp_name']);
$info = getimagesize($_FILES[$imageName]['tmp_name']);

This works well - allows resizing & conversion to png.

Now I need to do the same thing - but for downloaded images, e.g. given the url of an image online such as http://colorvisiontesting.com/images/plate%20with%205.jpg.

From the looks of it this can be done with CURL, but I can't quite work out how to then create an image object from it. This is what I have so far:

$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($c, CURLOPT_URL, $imageURL);
$curlImage = curl_exec($c);
$err  = curl_getinfo($c,CURLINFO_HTTP_CODE);
curl_close($c);

list ($width, $height, $type, $w)=getimagesize($curlImage);
$info = getimagesize($curlImage);

But this is failing at getimagesize - and I can't work out what the correct approach is here. Any ideas?

1

There are 1 answers

0
Dekel On BEST ANSWER

The getimagesize function works on filename (local or remote) but not on a string which represents the content of your image.

You can:

  1. Save that content to a local file (using file_put_contents, for example)
  2. Use the getimagesize function on the remote file (it should work).
  3. Use the getimagesizefromstring (which works the same as getimagesize but works in data and not filename)
  4. Use the imagecreatefromstring (which you need if you want to convert your stream/data to image (gd) resource, and then use the imagesx and imagesy on the resouce.