2016-05-19 9 views
0

私は壁紙のウェブサイトを構築していますので、ダウンロードする前に元の画像のサイズを変更できる必要があります。私は、画像のサイズを変更するためにこのコードを試してみました:PHPを使用してオンザフライで画像をトリミングする

//resize and crop image by center 
function resize_crop_image($max_width, $max_height, $source_file, $dst_dir, $quality = 80){ 
    $imgsize = getimagesize($source_file); 
    $width = $imgsize[0]; 
    $height = $imgsize[1]; 
    $mime = $imgsize['mime']; 

    switch($mime){ 
     case 'image/gif': 
      $image_create = "imagecreatefromgif"; 
      $image = "imagegif"; 
      break; 

     case 'image/png': 
      $image_create = "imagecreatefrompng"; 
      $image = "imagepng"; 
      $quality = 7; 
      break; 

     case 'image/jpeg': 
      $image_create = "imagecreatefromjpeg"; 
      $image = "imagejpeg"; 
      $quality = 80; 
      break; 

     default: 
      return false; 
      break; 
    } 

    $dst_img = imagecreatetruecolor($max_width, $max_height); 
    $src_img = $image_create($source_file); 

    $width_new = $height * $max_width/$max_height; 
    $height_new = $width * $max_height/$max_width; 
    //if the new width is greater than the actual width of the image, then the height is too large and the rest cut off, or vice versa 
    if($width_new > $width){ 
     //cut point by height 
     $h_point = (($height - $height_new)/2); 
     //copy image 
     imagecopyresampled($dst_img, $src_img, 0, 0, 0, $h_point, $max_width, $max_height, $width, $height_new); 
    }else{ 
     //cut point by width 
     $w_point = (($width - $width_new)/2); 
     imagecopyresampled($dst_img, $src_img, 0, 0, $w_point, 0, $max_width, $max_height, $width_new, $height); 
    } 

    $image($dst_img, $dst_dir, $quality); 

    if($dst_img)imagedestroy($dst_img); 
    if($src_img)imagedestroy($src_img); 
} 

そして、これはサイズ変更を行います。

resize_crop_image($width, $height, $image_URL, $save_URL) 

このコードは、私のために正常に動作しますが、私は保存するので、ユーザーのブラウザに出力を送信したいです何千もの余分な画像は不可能です。私が使用できるライブラリがありますが、第三者スニペットを使用したくありません。私の望むようにこのコードを変更する方法はありますか?おかげさまで

+0

しないでください。アップロード時に画像を一度*サイズ変更します。複数のサイズを作成して保存する。ディスク容量は、オンデマンドCPUのスケーリングよりもはるかに安価で、スケーラビリティに優れています。出典:24TBの画像があります。 – Sammitch

答えて

0

$ image関数では、出力先ディレクトリ(null)を指定しないでください。イメージストリームが作成されます。ユーザーあなただけの適切なヘッダーを設定し、出力をエコーする必要が

+0

これはすばやく簡単でした。ありがとうございましたjohn <3 –

+0

ちょうど1最後の質問...出力イメージの名前は、download.php、私のPHPファイルと同じ名前のようなものです。元のファイル名を返すにはどうすればよいですか?私は別のヘッダーを使用する必要がありますか? –

+0

正しいです、別のヘッダーはトリックを行います:Content-Disposition:attachment;ファイル名= FILENAME – John

0

に画像を送信する必要があります

header("Content-type:{$mime}"); 

Every PHP request "downloads a file" to the browser, more or less.ブラウザでの処理方法を指定するだけで済みます。だから、次のようなものを試してみてください:

header("Content-Type: $mime"); 
header("Content-Disposition: attachment; filename=$dst_img"); 
echo $dst_img; 

それはあなたのためにする必要があります。

+0

それはクールな男だった、私はちょうど画像を強制的にダウンロードする方法を尋ねていた!どうもありがとう! –

関連する問題