PHP等比压缩图片是指在不改变图片宽高比例的前提下,通过调整图片的宽度和高度来减小图片文件的大小。这种操作通常用于优化网站性能,减少页面加载时间。
<?php
function compress_image($source, $destination, $quality) {
$info = getimagesize($source);
if ($info['mime'] == 'image/jpeg') {
$image = imagecreatefromjpeg($source);
} elseif ($info['mime'] == 'image/gif') {
$image = imagecreatefromgif($source);
} elseif ($info['mime'] == 'image/png') {
$image = imagecreatefrompng($source);
}
$width = imagesx($image);
$height = imagesy($image);
// 计算等比压缩后的宽度和高度
$new_width = 800; // 可以根据需要调整
$new_height = round($height * ($new_width / $width));
$new_image = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
if (imageresolution($new_image) != 72) {
imageresolution($new_image, 72);
}
if ($info['mime'] == 'image/jpeg') {
imagejpeg($new_image, $destination, $quality);
} elseif ($info['mime'] == 'image/gif') {
imagegif($new_image, $destination);
} elseif ($info['mime'] == 'image/png') {
imagepng($new_image, $destination, 9 - ($quality / 10));
}
imagedestroy($image);
imagedestroy($new_image);
}
$source = 'path/to/source/image.jpg';
$destination = 'path/to/destination/image.jpg';
$quality = 75; // 质量范围为0-100
compress_image($source, $destination, $quality);
?>
php.ini
文件中设置memory_limit
。通过以上方法,可以有效地进行PHP等比压缩图片的操作,提升网站性能和用户体验。
领取专属 10元无门槛券
手把手带您无忧上云