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()、PHPがfopen関数で完全なURLを許可するように構成されていると仮定すると、cURLの代わりに使用できます。(デフォルトであると思います。)詳細については、file_get_contents()マニュアルページの「注意」セクションを参照してください。この関数バイナリセーフであるため、テキストファイルに加えて画像でも機能します。これを使用するために、cURL関数の6行すべてを次の行に置き換えました。

$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 に答える