将PHP脚本的图像输出保存为文件

时间:2016-10-14 12:43:39

标签: php image

我尝试让php脚本将生成的图像输出为.jpg文件:

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

回显在浏览器中显示正确的图像。 但是image.jpg没有保存。

我该如何做到这一点?

3 个答案:

答案 0 :(得分:1)

您需要为浏览器输出具有正确MIME类型的Content-Type标头,以便能够了解服务器正在发送的文件类型。

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

有关有效MIME类型的列表,请参阅http://php.net/manual/en/function.header.phphttps://www.sitepoint.com/web-foundations/mime-types-complete-list/

答案 1 :(得分:0)

使用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);

使用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);
}

答案 2 :(得分:0)

更改您的网址
http://www.photopost.com/photopost/showfull.php?photo=7541 //html document

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

然后使用其他答案中的代码或使用imagecreatefromjpeg http://php.net/manual/en/function.imagecreatefromjpeg.php