【发布时间】:2009-10-19 22:27:28
【问题描述】:
给定一个图像的直接链接,我如何使用 php 将实际图像存储在我在服务器上创建的文件夹中?
谢谢
【问题讨论】:
给定一个图像的直接链接,我如何使用 php 将实际图像存储在我在服务器上创建的文件夹中?
谢谢
【问题讨论】:
$image_url = 'http://example.com/image.jpg';
$image = file_get_contents($image_url);
file_put_contents('/my/path/image.jpg', $image);
简而言之,抓取图像,存储图像.. 就这么简单。
注意:allow_url_fopen php.ini 设置必须设置为 true 才能使上述示例正常工作。
【讨论】:
还有一种简单的方法:
$img = 'http://www.domain.com/image.jpg';
$img = imagecreatefromjpeg($img);
$path = '/local/absolute/path/images/';
imagejpeg($img, $path);
上面关于allow_url_fopen 的评论也适用于这个方法。如果您有一个相当严格的主机,您可能需要使用 cURL 来解决这个问题:
/**
* For when allow_url_fopen is closed.
*
* @param string $img The web url to the image you wish to dl
* @param string $fullpath The local absolute path where you want to save the img
*/
function save_image($img, $fullpath) {
$ch = curl_init ($img);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$binary_img = curl_exec($ch);
curl_close ($ch);
if (file_exists($fullpath)){
unlink($fullpath);
}
$fp = fopen($fullpath, 'x');
fwrite($fp, $binary_img);
fclose($fp);
}
【讨论】: