如何使用PHP实现图片的无损压缩和优化

admin10个月前javascript1031

<?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);

相关文章

阿里云OSS缩略图

?x-oss-process=image/resize,w_200...

js解密网站

https://www.sojson.com/jsjiemi.html...

Nuxt详解+案例

https://blog.csdn.net/M_wzz/article/details/121914443...

将不带www的域名301转向到带www的域名

nginx:if ( $host = "zhuoshenghuanbao.com" ) {rewrite ^/(.*)$ http://www.zhuoshenghuanbao.c...

vuejs学习官网

https://cn.vuejs.org/...

vscode压缩js代码的方法:

vscode压缩js代码的方法:1、在拓展商店里搜索“minify”,安装,安装成功后点重新加载2、使用:F1运行文件缩小器Minify压缩js代码。...

发表评论    

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。