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

admin2年前javascript1243

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

相关文章

vue-element-admin文档

https://panjiachen.gitee.io/vue-element-admin-site/zh/...

Masonry.js 生成无规则图片(高度不固定) 瀑布流

<script src="https://cdnjs.cloudflare.com/ajax/libs/masonry/4.2.2/masonry.pkgd.min.js&q...

jsPDF 文字、图片生成PDF(解决中文乱码)

https://www.cnblogs.com/andydao/p/18060680...

thinkphp 5.0.24漏洞

Thinkphp 5.0.24存在反序化漏洞,入口点在thinkphp/library/think/process/pipes/Windows.php中__destruct魔术方法。网上有很多讲解如何...

Nuxt详解+案例

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

paypal网站集成指南

原文链接:https://blog.csdn.net/wcjzff/article/details/81237551...

发表评论    

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