我刚刚编写了PHP代码来压缩图像大小。我的代码压缩图像但不是所有时间。在10%的情况下,它会增加图像大小。请告诉我为什么会这样?这是我的代码:(这里有两个函数,一个用于png图像,另一个用于jpg图像)
function compressImageSmall($source_url, $destination_url, $quality) {
//$quality :: 0 - 100
$info = getimagesize($source_url);
if ($info['mime'] == 'image/jpeg')
{
$image = imagecreatefromjpeg($source_url);
//save file
imagejpeg($image, $destination_url, $quality);//ranges from 0 (worst quality, smaller file) to 100 (best quality, biggest file). The default is the default IJG quality value (about 75).
//Free up memory
imagedestroy($image);
}
elseif ($info['mime'] == 'image/png')
{
$image = imagecreatefrompng($source_url);
//imagepng($image);
imageAlphaBlending($image, true);
imageSaveAlpha($image, true);
/* chang to png qulity*/
$png_quality = 9 - (($quality * 9 ) / 100 );
imagePng($image, $destination_url, $png_quality);//Compression level: from 0 (no compression) to 9.
//Free up memory
imagedestroy($image);
}
//return destination file
return $destination_url;
}
function compressImage($source_url, $destination_url, $quality) {
$info = getimagesize($source_url);
if ($info['mime'] == 'image/jpeg') $image = imagecreatefromjpeg($source_url);
elseif ($info['mime'] == 'image/gif') $image = imagecreatefromgif($source_url);
elseif ($info['mime'] == 'image/png') $image = imagecreatefrompng($source_url);
//save it
//echo '<pre>';print_r(imagejpeg($image));//
imagejpeg($image, $destination_url, $quality);
//return destination file url
return $destination_url;
}
答案 0 :(得分:-2)
内置像imagejpeg,imagepngImage等功能的Php可以方便地压缩图像。以下是图像压缩的完整代码示例:How to compress image file while uploading - PHP example ...