1

I try to have a php script output a generated image as .jpg file:

$url = 'http://www.photopost.com/photopost/showfull.php?photo=7541';
file_put_contents('image.jpg',file_get_contents($url));
$page = file_get_contents($url);
echo $page; 

The echo displays a correct image in the browser. but image.jpg is not saved.

How can I make this work ?

5

3 Answers 3

1

You need to output a Content-Type header with a proper MIME type for the browser to be able to understand what kind of file the server is sending.

header('Content-Type: image/jpeg');

Refer to http://php.net/manual/en/function.header.php and https://www.sitepoint.com/web-foundations/mime-types-complete-list/ for a list of valid MIME types.

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

2 Comments

I tried: code <?php header('Content-Type: image/jpeg'); $url = 'photopost.com/photopost/showfull.php?photo=7541'; file_put_contents('image.jpg',file_get_contents($url)); ?>
Have you specified a path for the image to be saved in? (I.e. file_put_contents('/tmp/image.jpg', $data);) The default path will probably not be writeable by the web server. Can the web server/PHP process write to that path? You need to provide the error for us to be able to help.
0

Getting image from url using curl :-

$profile_Image = 'http://www.photopost.com/photopost/showfull.php?photo=7541'; //image url
$userImage = 'myimg.jpg'; // renaming image
$path = '';  // your saving path
$ch = curl_init($profile_Image);
$fp = fopen($path . $userImage, 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
$result = curl_exec($ch);
curl_close($ch);
fclose($fp);

Getting image from url using file_get_contents :-

$profile_Image = 'http://www.photopost.com/photopost/showfull.php?photo=7541'; //image url
$userImage = 'myimg.jpg'; // renaming image
$path = '';  // your saving path
$thumb_image = file_get_contents($profile_Image);
if ($http_response_header != NULL) {
    $thumb_file = $path . $userImage;
    file_put_contents($thumb_file, $thumb_image);
}

1 Comment

Hi Jinandra, thansk for your help. This code downloads a file, bot not recognized on my pc as a valid jpg!
0

Change your url from

http://www.photopost.com/photopost/showfull.php?photo=7541 //html document

to

http://www.photopost.com/photopost/watermark.php?file=7541 //downloadable url

Then use code from other answers or use imagecreatefromjpeg http://php.net/manual/en/function.imagecreatefromjpeg.php

1 Comment

Dave thanks, this works! (my vote not yet visible due to low reputation)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.