閲覧頂きありがとうございます。
【概要】
質問内容としてはタイトルの通りとなります。
PHP GDを用いて、画像のリサイズを行いたい。詳細は以下。
・引数にwidthの指定のみの場合、縦横比を維持してwidth指定値でリサイズ。
・引数にheightの指定のみの場合、縦横比を維持してheight指定値でリサイズ。
【質問】
少々コードをおこしたのですが、以下のコードの場合、サイズの片方指定に対応できません。
(0を引数として渡すと比率算出時にエラーが出るため。)
サイズの片方指定に対応する場合はどのような考え方で処理を行うべきなのでしょうか?
本質問を解決するためのヒントを頂ければ幸いです。
PHP
1function resizeImg($orig_file, $resize_width=0, $resize_height=0) { 2 // GDライブラリがインストールされているか 3 if ( !extension_loaded( 'gd' ) ) { 4 // エラー処理 5 return false; 6 } 7 8 // 画像情報取得 9 $result = getimagesize( $orig_file ); 10 list( $orig_width, $orig_height, $image_type ) = $result; 11 12 // 画像をコピー 13 switch ($image_type) { 14 // 1 IMAGETYPE_GIF 15 // 2 IMAGETYPE_JPEG 16 // 3 IMAGETYPE_PNG 17 case 1 :$im = imagecreatefromgif( $orig_file );break; 18 case 2 :$im = imagecreatefromjpeg( $orig_file );break; 19 case 3 :$im = imagecreatefrompng( $orig_file );break; 20 default : // エラー処理 21 return false; 22 } 23 24 $ratio_orig = $orig_width / $orig_height;//元画像の比率計算 25 /*画像の比率を計算する*/ 26 if ( ($resize_width/$resize_height) > $ratio_orig ) { 27 $resize_width = $resize_height * $ratio_orig; 28 } else { 29 $resize_height = $resize_width / $ratio_orig; 30 } 31 32 // コピー先となる空の画像作成 33 $new_image = imagecreatetruecolor( $resize_width, $resize_height ); 34 if ( !$new_image ) { 35 // エラー処理 36 // 不要な画像リソースを保持するメモリを解放する 37 imagedestroy ( $im ); 38 return false; 39 } 40 41 // GIF、PNGの場合、透過処理の対応を行う 42 if (($image_type == 1) || ($image_type == 3)) { 43 imagealphablending ( $new_image, false ); 44 imagesavealpha( $new_image, true ); 45 $transparent = imagecolorallocatealpha ( $new_image, 255, 255, 255, 127 ); 46 imagefilledrectangle ( $new_image, 0, 0, $resize_width, $resize_height, $transparent ); 47 } 48 49 // コピー画像を指定サイズで作成 50 if ( !imagecopyresampled( $new_image, $im, 0, 0, 0, 0, $resize_width, $resize_height, $orig_width, $orig_height )) { 51 // エラー処理 52 // 不要な画像リソースを保持するメモリを解放する 53 imagedestroy ( $im ); 54 imagedestroy ( $new_image ); 55 return false; 56 } 57 58 // コピー画像を保存 59 // $new_image : 画像データ 60 // $new_fname : 保存先と画像名 61 // $quality :クオリティ 62 $new_fname = "保存先+ファイル名"; 63 $quality =80; 64 switch ($image_type) { 65 // 1 IMAGETYPE_GIF 66 // 2 IMAGETYPE_JPEG 67 // 3 IMAGETYPE_PNG 68 case 1 :$result = imagegif( $new_image, $new_fname, $quality );break; 69 case 2 :$result = imagejpeg( $new_image, $new_fname, $quality );break; 70 case 3 :$result = imagepng( $new_image, $new_fname, $quality );break; 71 default : // エラー処理 72 return false; 73 } 74 75 // 作業用データ削除 76 imagedestroy( $im ); 77 imagedestroy( $new_image ); 78 return $result; 79}

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/02/29 06:28