GD ライブラリを使用してサイズ変更された PNG 画像のサイズが元のサイズよりもはるかに大きい理由は非常に混乱しています。
これは、画像のサイズを変更するために使用しているコードです。
// create image from posted file
$src = imagecreatefrompng($file['tmp_name']);
// get original size of uploaded image
list($width,$height) = getimagesize($file['tmp_name']);
if($width>$maxImgWidth) {
// resize the image to maxImgWidth, maintain the original aspect ratio
$newwidth = $maxImgWidth;
$newheight=($height/$width)*$newwidth;
$newImage=imagecreatetruecolor($newwidth,$newheight);
// fill transparent with white
/*$white=imagecolorallocate($newImage, 255, 255, 255);
imagefill($newImage, 0, 0, $white);*/
// the following is to keep PNG's alpha channels
// turn off transparency blending temporarily
imagealphablending($newImage, false);
// Fill the image with transparent color
$color = imagecolorallocatealpha($newImage,255,255,255,127);
imagefill($newImage, 0, 0, $color);
// restore transparency blending
imagesavealpha($newImage, true);
// do the image resizing by copying from the original into $newImage image
imagecopyresampled($newImage,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
// write image to buffer and save in variable
ob_start(); // Stdout --> buffer
imagepng($newImage,NULL,5); // last parameter is compression 0-none 9-best (slow), see also http://www.php.net/manual/en/function.imagepng.php
$newImageToSave = ob_get_contents(); // store stdout in $newImageToSave
ob_end_clean(); // clear buffer
// remove images from php buffer
imagedestroy($src);
imagedestroy($newImage);
$resizedFlag = true;
}
次に、$newImageToSave を blob として mysql データベースに保存します。
アルファ チャネルを防止し、白い背景を設定するだけで、ファイル サイズに大きな変化はありませんでした。「圧縮」パラメータ (0 ~ 9) を設定してみましたが、それでも元のサイズよりも大きくなっています。
例
この画像(1058px*1296px) を 900px * 1102px にリサイズしました。結果は次のとおりです。
元のファイル: 328 KB
PNG (0): 3,79 MB
PNG (5): 564 KB
PNG (9): 503 KB
サイズ変更された画像のファイルサイズを小さくする方法のヒントをいただければ幸いです。
--
PS: ビット深度の可能性もあると思いましたが、ご覧のとおり、上の例の画像は 32 ビットですが、サイズ変更された画像は 24 ビットです。