2009-10-19 73 views

回答

4
$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,才能使上述示例正常工作。

+3

是的,这将工作,假设allow_url_fopen设置在php.ini中。如果不是,则必须使用CURL来获取图像,然后使用file_put_contents()写入图像。 – BraedenP 2009-10-19 22:35:30

+0

按照您的意见进行编辑:p – 2009-10-19 22:42:05

+0

非常感谢,效果很好 – 2009-10-19 22:48:44

2

还有的曾经简单的方法:

$img = 'http://www.domain.com/image.jpg'; 
$img = imagecreatefromjpeg($img); 
$path = '/local/absolute/path/images/'; 
imagejpeg($img, $path); 

关于于allow_url_fopen上述评论也正因为这个方法也是如此。如果你有一个相当严格的主机,你可能需要利用卷曲来解决这个问题:

/** 
* 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); 
} 
+0

您建议的第一种方法涉及比简单复制图像更多的开销。 – 2009-10-19 23:21:11

+0

唉,它可以让你用一些GD欺骗来操纵图像。 – 2009-10-19 23:51:19