PHP

PHPで画像を小さくリサイズし、容量も減らす方法(convert -resize)

PHPで指定した画像ファイルを小さくリサイズし、容量も減らす方法(convert -resize)をご紹介します。

画像を小さくリサイズし、容量も減らすHTMLの記述(画像を表示する呼び出し元)

※パラメータ「imgp=画像ファイルパス+ファイル名」で画像ファイルパスとファイル名をresize.phpに渡します。

<img src="resize.php?imgp=画像ファイルパス+ファイル名" alt="呼び出し元画像">

画像を小さくリサイズし、容量も減らすPHP(resize.phpファイル)の記述

※パラメータ「imgp=画像ファイルパス+ファイル名」で画像ファイルパスとファイル名を元に画像を小さくリサイズし、容量を減らします。phpのshell_execを使ってconvert -resizeコマンドを実行します。以下の記述内は全角文字(<、?、[、])を使ってる箇所があるのでご注意下さい。

<?php 
if (!empty($_GET['imgp'])) {
	$image_file = $_GET['imgp'];
}

$img = new mimage($image_file); 

$newWidth = 100; //画像のリサイズ幅(px)を指定
$newHeight = ($img->height / ($img->width / $newWidth));

header('Content-type: image/jpeg'); 
echo $img->resizeimage($newWidth, $newHeight); 


class mimage { 
    var $img_path; 
    var $width; 
    var $height; 
    var $font_file_path; 
  
    function mimage($image_path) { 
        $this->img_path = $image_path; 
        $image_info = getimagesize($this->img_path); 
        $this->width = $image_info[0]; 
        $this->height = $image_info[1]; 
    } 
  
    function resizeimage($max_w, $max_h, $new_file_dir = null, $new_file_name = null) { 
        if ($new_file_name) { 
            $new_file_path = $new_file_dir .'/'. $new_file_name; 
            $cmd = "convert ". $this->img_path ." -resize {$max_w}x{$max_h} {$new_file_path} "; 
            system($cmd); 
        } else { 
            $cmd = "convert ". $this->img_path ." -resize {$max_w}x{$max_h} -"; 
            return shell_exec($cmd); 
        } 
    } 
 
}
?>

まあ、も、画像の劣化とかを考えると、photoshopでリサイズ・圧縮した画像をそのまま表示した方が良いです。