3

我使用此脚本下载远程图像并调整其大小。在调整大小部分出现问题。它是什么?

<?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);



}
?>
4

1 回答 1

2

当我运行它时,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))){
于 2011-02-01T02:26:34.037 回答