PHP压缩图片(Webp)

文章介绍了如何使用PHP脚本对上传的图片进行压缩处理,支持JPEG、PNG和GIF格式,并演示了将图片转换为WebP格式的方法。
摘要由CSDN通过智能技术生成
<?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;
}
?>

  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值