views:

196

answers:

1

I want to be able to retrieve a remote image from a webserver, resample it, and then serve it up to the browser AND save it to a file. Here is what I have so far:

$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "$rURL");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_HEADER, 0);

// grab URL and pass it to the browser
$out = curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);

$imgRes = imagecreatefromstring($out);
imagejpeg($imgRes, $filename, 70);

header("Content-Type: image/jpg");
imagejpeg($imgRes, NULL, 70);
exit();

Update

Updated to reflect correct answer based on discussion below

A: 

You can fetch the file into a GD resource using imagecreatefromstring():

imagecreatefromstring() returns an image identifier representing the image obtained from the given data. These types will be automatically detected if your build of PHP supports them: JPEG, PNG, GIF, WBMP, and GD2.

from there, it's pretty straightforward using imagecopyresampled().

Output it using imagejpeg() or whichever output format suits you best.

Make one output with a file name:

imagejpeg($image_resource, "/path/to/image.jpg");

then send the same resource to the browser:

header("Content-type: image/jpeg");
imagejpeg($image_resource);

depending on the image's format, you may want to use the imagepng() or imagegif() functions instead.

You may want to work with different output formats depending on the input file type. You can fetch the input file type using getimagesize().

Remember that you can adjust the resulting JPEG image's quality using the $quality parameter. Default is 75% which can look pretty crappy.

Pekka
Thanks... I have updated my question now with your info... This requires two resamples of the image though as opposed to just one.. again it seems inefficient. What is a better way to do this?
Chris
@Chris Two resamples of the image? Why? You store the same resampled resource into the jpeg file, and serve it. Why would you do the resampling twice?
Pekka
Sorry I misinterpreted what you wrote. I have updated the code in my question. It creates the jpeg once with a lower quality. Presumably this is enough to lower the file size? After that I save it to file, but to serve it up I then need to read the file again, can I not store it temporarily in memory or is this a negligible overhead?
Chris
@Chris you don't need to do the `readfile`. Just `imagejpeg` it a second time with the file name parameter set to `null`. It will be output directly into the browser.
Pekka