保存图像输出从php脚本为文件


Save image output from php script as file

我尝试有一个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。

您需要输出一个带有适当MIME类型的Content-Type报头,以便浏览器能够理解服务器发送的是哪种文件。

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

参考http://php.net/manual/en/function.header.php和https://www.sitepoint.com/web-foundations/mime-types-complete-list/获取有效MIME类型的列表。

使用curl从url获取图像:-

$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从url获取图像:-

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

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

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

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