3

我有一个图像文件。示例:http: //images5.fanpop.com/image/photos/31100000/random-random-31108109-500-502.jpg

我想将图像保存到主机中名为 images-folder 的目录中。使用 PHP 执行此操作的最佳方法是什么?

4

3 回答 3

14

是的,这很简单。这是一个小cURL脚本来做到这一点:

$image_link = "http://images5.fanpop.com/image/photos/31100000/random-random-31108109-500-502.jpg";//Direct link to image
$split_image = pathinfo($image_link);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL , $image_link);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.A.B.C Safari/525.13");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
$response= curl_exec ($ch);
curl_close($ch);
$file_name = "images-folder/".$split_image['filename'].".".$split_image['extension'];
$file = fopen($file_name , 'w') or die("X_x");
fwrite($file, $response);
fclose($file);

这应该做你想要的。它将图像保存到目录中,然后将图像命名为random-random-31108109-500-502<-filename .jpg<-extension。

于 2013-02-27T16:35:58.447 回答
8

没有cURL更简单:

<?php
    $link= "http://images5.fanpop.com/image/photos/31100000/random-random-31108109-500-502.jpg";
    $destdir = 'images-folder/';
    $img=file_get_contents($link);
    file_put_contents($destdir.substr($link, strrpos($link,'/')), $img);
?>
于 2013-02-27T16:39:34.667 回答
1

这是另一个更容易理解的例子,直接来自我评论过的网站

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

http://www.edmondscommerce.co.uk/php/php-save-images-using-curl/

于 2013-02-27T16:38:25.227 回答