我正在创建上传文件的thumbail。
如果图像宽度和高度大于200,那么我将它们重新调整为200px。
这是我用来做的代码:
if (file_exists($old_file)) {
$path_parts = pathinfo($old_file);
$extension = $path_parts['extension'];
$filename_path = $filepath . $filename;
$destination_path = $filename_path;
if (strtolower($extension) == "jpg" || strtolower($extension) == "jpeg") {
$uploadedfile = $old_file;
$src = imagecreatefromjpeg($uploadedfile);
} else if (strtolower($extension) == "png") {
$uploadedfile = $old_file;
$src = imagecreatefrompng($uploadedfile);
} else {
$uploadedfile = $old_file;
$src = imagecreatefromgif($uploadedfile);
}
list($width, $height) = getimagesize($uploadedfile);
$newwidth = $Size['width'];
$newheight = $Size['height'];
if ($width <= $newwidth && $height <= $newheight) {
$newwidth = $width;
$newheight = $height;
$tmp = imagecreatetruecolor($width, $height);
} else {
if ($width > $height) {
$newheight = ($height / $width) * $newwidth;
$tmp = imagecreatetruecolor($newwidth, $newheight);
} else {
$newwidth = ($width / $height) * $newheight;
$tmp = imagecreatetruecolor($newwidth, $newheight);
}
}
if ((strtolower($extension) == "png") OR (strtolower($extension) == "gif")) {
imagealphablending($tmp, false);
imagesavealpha($tmp, true);
$transparent = imagecolorallocatealpha($tmp, 255, 255, 255, 127);
imagefilledrectangle($tmp, 0, 0, $newwidth, $newheight, $transparent);
}
imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
if (strtolower($extension) == "jpg" || strtolower($extension) == "jpeg") {
imagejpeg($tmp, $destination_path, 100);
} elseif (strtolower($extension) == "png") {
imagepng($tmp, $destination_path, 5);
} else {
imagegif($tmp, $destination_path);
}
chmod($destination_path, 0777);
imagedestroy($src);
imagedestroy($tmp);
ob_flush();
flush();
ob_end_flush();
return true;
} else {
return false;
}
它将大图像的大小重新调整为200px乘以200px,但图像大小在中增加(字节和kb等增加)。
我尝试上传8kb的png文件,新的缩略图文件大小是28kb?
尝试过谷歌搜索,但没有发现任何有用的
谢谢。
您的源图像经过压缩,解析后会得到一个未压缩的真彩色图像。然后将其保存为压缩级别5(在PNG的情况下),这是一个非常低的压缩级别,因此文件大小更大。
尝试更高的压缩,例如9。还可以尝试添加筛选器组合以减小文件大小(http://us3.php.net/manual/en/image.constants.php查找PNG_FILTER_*
)。
请参阅:http://us3.php.net/manual/en/function.imagepng.php
http://en.wikipedia.org/wiki/Portable_Network_Graphics#Compressionhttp://en.wikipedia.org/wiki/Portable_Network_Graphics#File_size_factors
GD库似乎没有提供任何接口来让您访问低级别的PNG数据,但理论上,您可以通过使用其他绑定或尝试手动读取来找到源压缩级别和过滤器。
http://www.libpng.org/pub/png/spec/1.2/PNG-Compression.htmlhttp://www.libpng.org/pub/png/spec/1.2/PNG-Filters.html
JPG和GIF也可能发生同样的情况。