<?php
$sourcePath = '../upload/IMG_20240107_192736.jpg';
$quality = 50;
$destinationPath = '../upload/1.jpg';
compressImage($sourcePath,$destinationPath,$quality);
$destinationPathWebp = '../upload/2.webp';
saveWebp($sourcePath,$destinationPathWebp);
echo $destinationPath;
// 压缩图片(Webp)
// $sourcePath, 源路径
// $destinationPath, 目标路径
function saveWebp($sourcePath, $destinationPath) {
$imageInfo = getimagesize($sourcePath);
$imageType = $imageInfo[2];
if ($imageType == IMAGETYPE_JPEG) {
$image = imagecreatefromjpeg($sourcePath);
imagewebp($image, $destinationPath);
} elseif ($imageType == IMAGETYPE_PNG) {
$image = imagecreatefrompng($sourcePath);
imagewebp($image, $destinationPath);
} elseif ($imageType == IMAGETYPE_GIF) {
$image = imagecreatefromgif($sourcePath);
imagewebp($image, $destinationPath);
}
imagedestroy($image);
return true;
}
// 压缩图片
// $sourcePath, 源路径
// $destinationPath, 目标路径
// $quality, 质量
function compressImage($sourcePath, $destinationPath, $quality) {
$imageInfo = getimagesize($sourcePath);
$imageType = $imageInfo[2];
if ($imageType == IMAGETYPE_JPEG) {
$image = imagecreatefromjpeg($sourcePath);
imagejpeg($image, $destinationPath, $quality);
} elseif ($imageType == IMAGETYPE_PNG) {
$image = imagecreatefrompng($sourcePath);
imagepng($image, $destinationPath, 9 - round($quality * 0.08));
} elseif ($imageType == IMAGETYPE_GIF) {
$image = imagecreatefromgif($sourcePath);
imagegif($image, $destinationPath);
}
imagedestroy($image);
return true;
}
?>
PHP压缩图片(Webp)
文章介绍了如何使用PHP脚本对上传的图片进行压缩处理,支持JPEG、PNG和GIF格式,并演示了将图片转换为WebP格式的方法。
摘要由CSDN通过智能技术生成