9

我很困惑为什么使用 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 保存为 mysql 数据库中的 blob。

我试图阻止 alpha 通道,只设置白色背景,文件大小没有显着变化。我尝试设置“压缩”参数(0 到 9),但仍然比原来的大。

示例
我拍摄了这张图片(1058px*1296px) 并将其调整为 900px * 1102px。这些是结果:

原始文件:328 KB
PNG(0):3,79 MB
PNG(5):564 KB
PNG(9):503 KB

任何提示如何使调整后的图像的文件大小更小,我们都表示赞赏。

--

PS:我认为它可能是位深度,但如您所见,上面的示例图像有 32 位,而调整大小的图像是 24 位。

4

1 回答 1

13

您调用的大多数用于缩小图像、等的函数都不会imagefill导致imagealphablending文件大小增加。

保持透明使用imagecreate,而不是imagecreatetruecolor只做一个简单的调整大小

$file['tmp_name'] = "wiki.png";
$maxImgWidth = 900;
// 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) {
    $newwidth = $maxImgWidth;
    $newheight = ($height / $width) * $newwidth;
    $newImage = imagecreate($newwidth, $newheight);
    imagecopyresampled($newImage, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    imagepng($newImage, "wiki2.png", 5); 
    imagedestroy($src);
    imagedestroy($newImage);
    $resizedFlag = true;
}

最终大小:164KB

于 2012-11-06T19:31:13.557 回答