得到了一个php脚本,从url下载许多图像,我可以使脚本工作更快


Got a php script that downloads many images from url, can i make the script work faster?

首先创建一个包含图像的url数组(1 url = 1 image, url中没有其他内容):

$image_endings = array();
for($x=1;$x<=25;$x++) {
    for($y=1;$y<=48;$y++) {
        $image_endings[] ="${x}n${y}w.png";
    }
}

现在我运行每个url,如果该url存在,我下载图像:

foreach ($image_endings as $se){
    $url = 'http://imgs.xkcd.com/clickdrag/'.$se;
if (@GetImageSize($url)) {
//echo  "image exists ";
    $img = file_get_contents($url);
    file_put_contents("tiles/".$se,$img);
    $width = 50;
    $height = 50;
    $filename = 'tiles/'.$se;
    $image = imagecreatefrompng ( $filename );
    $new_image = imagecreatetruecolor ( $width, $height ); // new wigth and height
    imagealphablending($new_image , false);
    imagesavealpha($new_image , true);
    imagecopyresampled ( $new_image, $image, 0, 0, 0, 0, $width, $height, imagesx ( $image ), imagesy ( $image ) );
    $image = $new_image;
    // saving
    imagealphablending($image , false);
    imagesavealpha($image , true);
    imagepng ( $image, $filename );
} else {
// echo  "image does not exist ";

}

这个脚本的问题-它需要~5分钟才能完全完成。我想知道我能不能让它跑快一点?

与其检查每一个GetImageSize,因为这可能会花费不必要的时间,不如只检查一次(当你去取它的时候):

...
foreach ($image_endings as $se){
    $url = 'http://imgs.xkcd.com/clickdrag/'.$se;
/* Don't do this... time consuming...
if (@GetImageSize($url)) {
echo  "image exists ";
*/

$img = file_get_contents($url);
// Check here if it existed.
if ($img !== false) {
    file_put_contents("tiles/".$se,$img);
...

根据@GeraldSchneider的评论…file_put_contents(...)是必需的吗?