卷曲并调整远程图像的大小

我使用此脚本下载并调整远程图像的大小。在调整大小部分出了问题。它是什么?
<?php
$img[]='http://i.indiafm.com/stills/celebrities/sada/thumb1.jpg';
$img[]='http://i.indiafm.com/stills/celebrities/sada/thumb5.jpg';
foreach($img as $i){
    save_image($i);
    if(getimagesize(basename($i))){
        echo '<h3 style="color: green;">Image ' . basename($i) . ' Downloaded OK</h3>';
    }else{
        echo '<h3 style="color: red;">Image ' . basename($i) . ' Download Failed</h3>';
    }
}

function save_image($img,$fullpath='basename'){
    if($fullpath=='basename'){
        $fullpath = basename($img);
    }
    $ch = curl_init ($img);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
    $rawdata=curl_exec($ch);
    curl_close ($ch);




    // now you make an image out of it

    $im = imagecreatefromstring($rawdata);

    $x=300;
    $y=250;

    // then you create a second image, with the desired size
    // $x and $y are the desired dimensions
    $im2 = imagecreatetruecolor($x,$y);


    imagecopyresized($im2,$im,0,0,0,0,$x,$y,imagesx($im),imagesy($im));


    imagecopyresampled($im2,$im,0,0,0,0,$x,$y,imagesx($im),imagesy($im));

    // delete the original image to save resources
    imagedestroy($im);



    if(file_exists($fullpath)){
        unlink($fullpath);
    }
    $fp = fopen($fullpath,'x');
    fwrite($fp, $im2);
    fclose($fp);

    // remember to free resources
imagedestroy($im2);



}
?>
    
已邀请:
当我运行它时,PHP给了我以下错误:   警告:fwrite()期望参数2为第53行的字符串,资源给定....
fwrite()
将字符串写入文件。您想使用GD功能
imagejpeg()
将GD资源保存到文件中。当我改变时它对我有用
$fp = fopen($fullpath,'x');
fwrite($fp, $im2);
fclose($fp);
imagejpeg($im2, $fullpath);
在一个不相关的说明中,如果您正在使用cURL进行抓取文件,则可以简单地使用
file_get_contents()
而不是cURL,假设PHP配置为允许fopen函数中的完整URL。 (我相信它是默认的。)有关详细信息,请参阅file_get_contents()手册页上的“注释”部分。该函数是二进制安全的,因此除了文本文件之外,它还可以处理图像。为了使用它,我只用这一行替换了cURL函数的所有六行:
$rawdata = file_get_contents($img);
更新: 在回答下面的问题时,您可以在数组键中为它们指定新的文件名,如下所示:
<?php
$img['img1.jpg']='http://i.indiafm.com/stills/celebrities/sada/thumb1.jpg';
$img['img2.jpg']='http://i.indiafm.com/stills/celebrities/sada/thumb5.jpg';
foreach($img as $newname => $i){
    save_image($i, $newname);
    if(getimagesize(basename($newname))){
    

要回复问题请先登录注册