GDによる画像読み書き簡易化関数の作成
オンラインの phpマニュアルには、user note として、各関数解説ページの下部に、利用法や、注意点などが載っている。しかし、どこに何がかいてあるか探すのも一苦労なので、GD関連で有用なのを自作関数にしてみた。
imagecreatefromfile($path, $user_functions = false)
* 画像ファイル名を第1引数$pathで与え、 file type を自動判定して、image取り込み関数を切り換えて、GD イメージオブジェクトを作成する
参考url http://jp2.php.net/manual/ja/function.imagecreate.php#81831
※ $user_functions は、ビットマップ取り込み用関数も利用するかどうかの指定。 これを true としてビットマップ形式も対象とする時は、bmp読み書き関数で作成した関数をincludeしますので、「gd_bmp_util.php」で保存して同一ディレクトリーに置いて下さい。/* http://jp2.php.net/manual/ja/function.imagecreate.php#81831 * 画像ファイルパス指定のみで、typeを判断し取り込み関数を自動切り替えしてGDイメージオブジェクトに取り込む * @param $path : 画像ファイルパス、実行中phpからアクセスできるパス * @param $user_functions : ビットマップ取り込み用関数も利用するかどうか 省略時ビットマップ以外のGDが対応している画像タイプのみ true : ビットマップ用関数ファイルgd_bmp_util.phpをincludeして、ビットマップ画像を取り込む * @return imagecreatefrompng などで作成したGD イメージオブジェクト 作成失敗時 false */ function imagecreatefromfile($path, $user_functions = false){ $info = @getimagesize($path); if(!$info){ return false; } $functions = array( IMAGETYPE_GIF => 'imagecreatefromgif', IMAGETYPE_JPEG => 'imagecreatefromjpeg', IMAGETYPE_PNG => 'imagecreatefrompng', IMAGETYPE_WBMP => 'imagecreatefromwbmp', IMAGETYPE_XBM => 'imagecreatefromwxbm' ); if($user_functions){ require_once('gd_bmp_util.php'); $functions[IMAGETYPE_BMP] = 'ImageCreateFromBMP'; } if(!isset($functions[$info[2]])){ return false; } if(!function_exists($functions[$info[2]])){ return false; } return $functions[$info[2]]($path); }
image_output($image, $ftype=IMAGETYPE_PNG, $the3rd=null, $caching=null, $user_functions = false)
* 第1引数で渡したGDイメージオブジェクトを、第2引数で画像タイプを指定して、ブラウザへ画像出力。
第3引数は、画像typeによって、圧縮率などを指定。
第4引数で、ブラウザにキャッシュさせるかどのうかのheader出力を切り換え。
参考url http://jp2.php.net/manual/ja/ref.image.php#55824
※ $user_functions は、ビットマップ取り込み用関数も利用するかどうかの指定。 これを true としてビットマップ形式も対象とする時は、bmp読み書き関数で作成した関数をincludeしますので、「gd_bmp_util.php」で保存して同一ディレクトリーに置いて下さい。/* * 画像タイプを指定して、ブラウザへ画像出力。 * @param $image :ImageCreateTrueColorなどで作ったGDイメージオブジェクト を指定 * @param $ftype :IMAGETYPE 定数で指定, default IMAGETYPE_PNG 第4引数 $user_functionsがtrueならば IMAGETYPE_BMP も使える * @param $the3rd :各タイプ画像出力時の第3引数 imagegif 第3引数無し imagejpeg ( resource $image [, string $filename [, int $quality ]] ) 第3 quality : 0(品質は最低 ですが、ファイルはより小さい)から100(品質は最高ですが、ファイルは 最大)の範囲で指定します。デフォルトは IJG 品質値(75)です imagepng ( resource $image [, string $filename [, int $quality [, int $filters ]]] ) 第3 quality :圧縮レベル。0 (圧縮しない) から 9 までの値で指定します, php5.1.2以降で使用可能, default 6 程度の圧縮 第4引数$filtersはここでは省略とする。 imagewbmp ( resource $image [, string $filename [, int $foreground ]] ), imagexbm ( resource $image , string $filename [, int $foreground ] ) 第3 $foreground :imagecolorallocate() で 取得した ID ,デフォルトの前景色は黒 * @param $caching : cache control header 出力の切り分け、 null または省略 :cache関連header無し、 'nocache' : nocache用のheaderを出力、 'cached' : ブラウザやプロキシにキャッシュさせるためのheader出力。 * @param $user_functions : ビットマップ形式 .bmp を指定したいとき(imagewbmpでは、windowsのビットマップ形式ではないので) 省略時ビットマップ以外のGDが対応している画像タイプのみ true : ビットマップ用関数ファイルgd_bmp_util.phpをincludeして、ビットマップ形式で出力 $user_functionsをtrueにするときは、手前の引数は、nullも明示して全部指定しないといけない。 * @return : エラーがなければブラウザへ画像出力してプログラムが終了する。 画像resourceが無いなど指定不良時はfalseを返す。プログラムは終了しない。 */ function image_output($image, $ftype=IMAGETYPE_PNG, $the3rd=null, $caching=null, $user_functions = false){ if(!$image){ return false; } $functions = array( IMAGETYPE_GIF => 'imagegif', IMAGETYPE_JPEG => 'imagejpeg', IMAGETYPE_PNG => 'imagepng', IMAGETYPE_WBMP => 'imagewbmp', IMAGETYPE_XBM => 'imagexbm' ); if($user_functions){ require_once('gd_bmp_util.php'); $functions[IMAGETYPE_BMP] = 'imageBMP'; } if(!isset($functions[$ftype])){ return false; } ob_start(); // buffer に画像データ出力 if(IMAGETYPE_GIF==$ftype or IMAGETYPE_BMP==$ftype or $the3rd===null ){ $functions[$ftype]($image ); }else{ $functions[$ftype]($image, NULL, $the3rd); } // cache control header 出力 if( 'nocache' === $caching ){ header("Expires: Mon, 26 Jul 1997 09:00:00 GMT"); // とりあえず過去で有ればよい header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // pragma はHTTP1.0用。cache-control はHTTP1.1用 header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); }else if( 'cached' === $caching ){ header("HTTP/1.1 202 Accepted"); // opera skipped loading header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Expires: ". gmdate("D, d M Y H:i:s", time()+3000000) . " GMT"); // 正味期限は一ヶ月以内にすべきらしい。。。 header("Cache-Control: max-age=10000000, s-maxage=1000000, proxy-revalidate, must-revalidate"); // ISP caches for 1 million seconds > 60*60*24*11days } // 画像用header header("Content-type: " . image_type_to_mime_type($ftype) ); // Tell the browser the number of bytes that have been // written to the buffer. header("Content-Length: " . ob_get_length()); // Now send the buffer's contents to the browser and turn off // output buffering. ob_end_flush(); imagedestroy($image); exit; // 他の出力はさせない }
resize($im,$maxwidth=150,$maxheight=100, $type=IMAGETYPE_JPEG)
* ImageCreateTrueColorなどで作ったGDイメージオブジェクト を指定し、画像をリサイズしサムネイル作成。縦横比は変えないで、$maxwidth,$maxheight以内にする
参考url http://jp2.php.net/manual/ja/function.imagecreate.php#48738
gifとpngの透過画像のリサイズ法を見つけたので、改良版作成[2009/10/26] →公開サーバー移動[2012/08/28]
透過設定参考url http://www.mediumexposure.com/techblog/smart-image-resizing-while-preserving-transparency-php-and-gd-library
参考url2 http://www.c-styles.jp/archives/204/* * 画像のリサイズ、サムネイル作成、縦横比は変えないで、最大$maxwidth,$maxheight以内にする * @param $image is the source image(推奨 TrueColor イメージ) * @param $maxwidth :最大横 default=150 * @param $maxheight:最大縦 default=100 * @param $type : $imageの元データタイプ: IMAGETYPE_PNG または、IMAGETYPE_GIF のとき、透過性設定を取り出すために必要。省略時は透過性を保持しない。 * * @return : 新規作成 imagecreatetruecolor で作成した画像リソース */ function resize($image,$maxwidth=150,$maxheight=100, $type=IMAGETYPE_JPEG){ //calculate thumb size : サムネイルサイズの計算 $ow = imagesx($image); $oh = imagesy($image); $new_h = $oh; $new_w = $ow; if($oh > $maxheight || $ow > $maxwidth){ $new_h = ($oh > $ow) ? $maxheight : $oh*($maxwidth/$ow); $new_w = $new_h/$oh * $ow; } //create for resize $image_resized = ImageCreateTrueColor($new_w,$new_h); // preserving-transparency $trans = false; if ( ($type == IMAGETYPE_GIF) || ($type == IMAGETYPE_PNG) ) { $trnprt_indx = imagecolortransparent($image); // If we have a specific transparent color if ($trnprt_indx >= 0) { $trans = true; // Get the original image's transparent color's RGB values $trnprt_color = imagecolorsforindex($image, $trnprt_indx); // Allocate the same color in the new image resource $trnprt_indx = imagecolorallocate($image_resized, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']); // Completely fill the background of the new image with allocated color. imagefill($image_resized, 0, 0, $trnprt_indx); // Set the background color for new image to transparent imagecolortransparent($image_resized, $trnprt_indx); } // Always make a transparent background color for PNGs that don't have one allocated already elseif ($type == IMAGETYPE_PNG) { $trans = true; // Turn off transparency blending (temporarily) imagealphablending($image_resized, false); // Create a new transparent color for image $color = imagecolorallocatealpha($image_resized, 0, 0, 0, 127); // Completely fill the background of the new image with allocated color. imagefill($image_resized, 0, 0, $color); // Restore transparency blending imagesavealpha($image_resized, true); } } //resize and copy image: // 透過背景を維持するには imagecopyresized 。品質保持(文字が掠れない)ためには imagecopyresampled if($trans){ imagecopyresized($image_resized, $image, 0,0,0,0, $new_w, $new_h, $ow, $oh); }else{ imagecopyresampled($image_resized, $image, 0,0,0,0, $new_w, $new_h, $ow, $oh); } return $image_resized; }
make_blank($width, $height, $r=0,$g=0,$b=0, $transparent=1)
* 空画像作成用、背景色や透過設定までの一連の作業をサブルーチン化/* * 空画像作成 * @param $width, $height : 幅と高さ、int型、pixel数 * @param $r,$g,$b : 背景色、色成分、赤緑青の順、int型 0-255 で指定。省略時0 * @param $transparent : 透過設定、「1」透過する、「0 または false」透過しない。 省略時1=背景色を透過する * @return : imagecreatetruecolor で作成した画像リソース */ function make_blank($width, $height, $r=0,$g=0,$b=0, $transparent=1){ if( $width <1 ){ $width = 1;} if( $height <1 ){ $height = 1;} $canvas = imagecreatetruecolor ($width, $height); $bgc = imagecolorallocate ($canvas, $r,$g,$b ); imagefilledrectangle ($canvas, 0, 0, $width, $height, $bgc); if($transparent){ imagecolortransparent($canvas,$bgc); } return $canvas; }
nocache_header()
ブラウザにキャッシュさせないheader を出力する
先に文字列が出力されると、もうheader送信ができません。 php.iniまたはプログラム先頭で ob_start() をおこなうなどにより、バッファーリングを行っておくと、よいです。
参考url http://jp2.php.net/manual/ja/ref.image.php#55824/* * ブラウザにキャッシュさせないheader出力 */ function nocache_header(){ header("Expires: Mon, 26 Jul 1997 09:00:00 GMT"); // とりあえず過去で有ればよい header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // pragma はHTTP1.0用。cache-control はHTTP1.1用 header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); }
cached_header()
ブラウザやproxyにもcacheさせるheader出力して、web trafic軽減を図る。閲覧ユーザーにとっても、2回目以降の表示が早くなります。
参考url http://jp2.php.net/manual/ja/ref.image.php#13058/* * ブラウザやproxyにもcacheさせるheader出力:web trafic軽減 * @param $day : キャッシュ期限(ブラウザー保存期限) int 型 日数指定 省略時 30日、 1未満の時は、強制的に 1 とします。 */ function cached_header($day=30){ if($day<1){ $day=1; } $exp = time()+ 86400*$day ; header("HTTP/1.1 202 Accepted"); // opera skipped loading header("Last-Modified: " . gmdate("D, d M Y H:i:s" ) . " GMT"); header("Expires: ". gmdate("D, d M Y H:i:s", $exp) . " GMT"); header("Cache-Control: max-age=10000000, s-maxage=1000000, proxy-revalidate, must-revalidate"); // ISP caches for 1 million seconds > 60*60*24*11days }
[設置日 2012-08-28] [最終更新日 ]