画像ファイルを指定容量ぎりぎりに圧縮する

画像ファイルを指定容量以下ぎりぎりに圧縮して出力する方法です。

JPEG、PNGでは、画像の圧縮比が可変のため容量に合わせて圧縮比を変えることができます。
GIFでは仕様上、容量を少なくするには使用する色数を減らしたり画像を単純化したりするためこのコードでは対応できません。

<?php
/* ================================
 * 画像を指定容量以下に圧縮する
 *
 * @create  2009/06/12
 * @author  pentan
 * @url     http://pentan.info/
 *
 * Copyright (c) 2009 pentan.info All Rights Reserved.
 * 著作権表示部分の変更削除は禁止です
 * ================================
 */
// 最大容量 (バイト単位)
$limit=100*1024;
// 読み込み画像のパス jpeg/pngに対応
$img_path="test.jpg";

// ファイルの存在チェック
if(empty($img_path) || !is_file($img_path)){
  header("HTTP/1.x 404 Not Found");
  exit;
}

list($img_width,$img_height,$type)=getimagesize($img_path);

// ファイルの種類判別
switch( $type ){
  case 2:
    $img_input_func ="imagecreatefromjpeg";
    $img_output_func="imagejpeg";
    $img_contenttype="image/jpeg";
    $start=100;
    $end=1;
    $step=-5;
    break;
  case 3:
    $img_input_func ="imagecreatefrompng";
    $img_output_func="imagepng";
    $img_contenttype="image/png";
    $start=0;
    $end=9;
    $step=1;
    break;
  default:
    header("HTTP/1.x 404 Not Found");
    exit;
    break;
}

// ファイル読み込み
if(!($src=@$img_input_func($img_path))){
  header("HTTP/1.x 404 Not Found");
  exit;
}

$quality=$start;
while(true){
  ob_start();
  $img_output_func($src,null,$quality);
  $quality+=$step;
  $outfile=ob_get_clean();
  $file_size=strlen($outfile);
  if($file_size <= $limit)break;
  if($start <= $quality && $quality <= $end)continue;
  if($end <= $quality && $quality <= $start)continue;
  break;
}
imagedestroy($src);

// 圧縮限界チェック
if($file_size > $limit){
  header("HTTP/1.x 404 Not Found");
  exit;
}

header("Content-Type: " . $img_contenttype);
echo $outfile;

関連記事

スポンサーリンク

各メーカーのルーターのID・パスワードの一覧

ホームページ製作・web系アプリ系の製作案件募集中です。

上に戻る