PHP中,有三种方法可以采集图片,注意:这几个方法,都要在php.ini中打开“allow_url_fopen”。

  • 1.利用Curl
  • 2.用File Function
  • 3.利用GD Library

一、Curl的用法

<?php
$my_img[]='http://images.askmen.com/galleries/cobie-smulders/picture-1-134686094208.jpg';

$my_img[]='http://images.askmen.com/galleries/demi-lovato/picture-1-134212249378.jpg';

$fullpath = "images_saved";

foreach($my_img as $i){
    image_save_from_url($i,$fullpath);

    if(getimagesize($fullpath."/".basename($i))){
        echo '<h3 style="color: green;">Image ' . basename($i) . ' Downloaded Successfully</h3>';
    }else{
        echo '<h3 style="color: red;">Image ' . basename($i) . ' Download Failed</h3>';
    }
}

function image_save_from_url($my_img,$fullpath){
    if($fullpath!="" && $fullpath){
        $fullpath = $fullpath."/".basename($my_img);
    }
    $ch = curl_init ($my_img);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
    curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
    $rawdata=curl_exec($ch);
    curl_close ($ch);
    if(file_exists($fullpath)){
        unlink($fullpath);
    }
    $fp = fopen($fullpath,'x');
    fwrite($fp, $rawdata);
    fclose($fp);
}
?>

二、File 的用法

<?php 
function save_from_url($inPath,$outPath)
{ //Download images from remote server
    $in=    fopen($inPath, "rb");
    $out=   fopen($outPath, "wb");
    while ($chunk = fread($in,8192))
    {
        fwrite($out, $chunk, 8192);
    }
    fclose($in);
    fclose($out);
}

save_from_url('http://yousite.com/image1.jpg','your_new_image.jpg');
?>

三、GD library functions用法

<?php
$my_server_img = 'http://images.askmen.com/galleries/cobie-smulders/picture-1-134686094208.jpg';
$img = imagecreatefromjpeg($my_server_img);
$path = 'images_saved/';
imagejpeg($img, $path);
?>

PS:第二个方法curl比较常用,XHE中在Browser中打开图片,直接保存在文件夹里就行。