如何使用PHP实现图片的无损压缩和优化
<?php
function compressImage($source, $destination, $maxWidth, $maxHeight, $quality) {
$info = getimagesize($source);
$width = $info[0];
$height = $info[1];
// 计算缩放比例
$scale = min($maxWidth/$width, $maxHeight/$height);
// 计算缩放后的宽度和高度
$newWidth = $width * $scale;
$newHeight = $height * $scale;
// 创建缩略图
$thumb = imagecreatetruecolor($newWidth, $newHeight);
// 根据原图类型进行相应的处理
if ($info['mime'] == 'image/jpeg') {
$sourceImage = imagecreatefromjpeg($source);
} elseif ($info['mime'] == 'image/png') {
$sourceImage = imagecreatefrompng($source);
} elseif ($info['mime'] == 'image/gif') {
$sourceImage = imagecreatefromgif($source);
} else {
return false;
}
// 将原图复制到缩略图中
imagecopyresampled($thumb, $sourceImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
// 保存缩略图
if ($info['mime'] == 'image/jpeg') {
imagejpeg($thumb, $destination, $quality);
} elseif ($info['mime'] == 'image/png') {
imagepng($thumb, $destination, 9);
} elseif ($info['mime'] == 'image/gif') {
imagegif($thumb, $destination);
}
return true;
}
// 使用示例
$sourceImage = 'source.jpg';
$destinationImage = 'compressed.jpg';
$maxWidth = 800;
$maxHeight = 600;
$quality = 75;
compressImage($sourceImage, $destinationImage, $maxWidth, $maxHeight, $quality);