28

Possible Duplicate:
Saving image from PHP URL

I have an image as a url link from the 3rd party web thumb site (IE http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com) What I would like to do is run a script that takes the image and saves it in a directory on my server using php. How to do this? would I use File Write?

3

2 Answers 2

56

No need to create a GD resource, as someone else suggested.

$input = 'http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com';
$output = 'google.com.jpg';
file_put_contents($output, file_get_contents($input));

Note: this solution only works if you're setup to allow fopen access to URLs. If the solution above doesn't work, you'll have to use cURL.

Sign up to request clarification or add additional context in comments.

2 Comments

What if image format is not jpg. Partially correct answer
For png <?php $im = imagecreatefrompng($ouput); header('Content-Type: image/png'); imagepng($im); imagedestroy($im); ?>
22

Note: you should use the accepted answer if possible. It's better than mine.

It's quite easy with the GD library.

It's built in usually, you probably have it (use phpinfo() to check)

$image = imagecreatefromjpeg("http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com");

imagejpeg($image, "folder/file.jpg");

The above answer is better (faster) for most situations, but with GD you can also modify it in some form (cropping for example).

$image = imagecreatefromjpeg("http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com");
imagecopy($image, $image, 0, 140, 0, 0, imagesx($image), imagesy($image));
imagejpeg($image, "folder/file.jpg");

This only works if allow_url_fopen is true (it is by default)

3 Comments

This only works if allow_url_fopen is true.
@Ólafur Waage sure, but by the same token, cURL only works if the curl extension is available and enabled on your system.
This is forcing GD to decode and encode the image for no reason. That also means it's lossy, and imagejpeg uses only 75% quality by default. All the OP asked for is a download (a bit-for-bit copy).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.