<?php
// 压缩图片的示例代码
function compressImage($source, $destination, $quality) {
// 获取图片信息
$info = getimagesize($source);
if ($info === false) {
return false;
}
// 根据图片类型创建相应的图像资源
$image = imagecreatefromstring(file_get_contents($source));
if ($image === false) {
return false;
}
// 创建一个新的图像资源,用于保存压缩后的图片
$imageResized = imagescale($image, $info[0], $info[1]);
// 根据图片类型保存压缩后的图片
switch ($info['mime']) {
case 'image/jpeg':
imagejpeg($imageResized, $destination, $quality);
break;
case 'image/png':
$pngQuality = 9 - (int)(0.09 * $quality); // PNG 质量转换
imagepng($imageResized, $destination, $pngQuality);
break;
case 'image/gif':
imagegif($imageResized, $destination);
break;
default:
return false;
}
// 释放内存
imagedestroy($image);
imagedestroy($imageResized);
return true;
}
// 示例用法
$sourcePath = 'path/to/source/image.jpg';
$destinationPath = 'path/to/destination/image.jpg';
$compressionQuality = 75; // 图片质量,范围是 0-100
if (compressImage($sourcePath, $destinationPath, $compressionQuality)) {
echo "图片压缩成功";
} else {
echo "图片压缩失败";
}
?>
getimagesize 函数获取图片的尺寸和类型。imagecreatefromstring 函数将图片内容转换为图像资源。imagescale 函数调整图片大小(这里保持原尺寸不变)。imagedestroy 函数释放不再需要的图像资源。compressImage 函数来压缩图片。上一篇:php获取post请求参数
下一篇:php判断字符串长度
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站