2011-01-31 7 views
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); 



} 
?> 
+0

どのようなエラーが表示されますか? – Merijn

+0

テストケースはどこですか? – Greg

+0

ダウンロードが失敗しました – mark

答えて

2

私はそれを実行すると、PHPは私に次のエラーを与える:

Warning: fwrite() expects parameter 2 to be string, resource given ... on line 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を許可するように設定されていると仮定します。 (私はそれがデフォルトであると信じています。)詳細については、the file_get_contents() manual pageの注記セクションを参照してください。関数バイナリセーフなので、テキストファイルに加えてイメージでも動作します。これを使用するには、私はちょうどこのラインでの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))){ 
+0

$ img [] = 'http://i.indiafm.com/stills/celebrities/sada/thumb1.jpg';画像のカスタム名を定義することは可能でしょうか? 広告は何らかの方法で関数に渡されますか? – mark

+0

@mark上記の答えで追加されたコードは、十分なスペースがないためです。 – Wiseguy

関連する問題