一键快捷压缩单张图片php脚本
复制下列代码,命名为yasuo.php
,访问即可,代码里自己修改文件名
php 7.4亲测通过,其他5.X版本不确定能用,自行测试哈
有的时候只想压缩单张图片,但是不想直接下载下来,麻烦,所以用这个办法
<?php
// 定义一个函数来处理图片压缩
function compressImage($inputPath, $outputPath, $compressionQuality = 75) {
// 打开图片
$image = imagecreatefromjpeg($inputPath);
// 获取原始图像的宽度和高度
$width = imagesx($image);
$height = imagesy($image);
// 设置新图像的压缩比例(例如压缩到原来的一半)
$new_width = $width / 2;
$new_height = $height / 2;
// 创建一个空白画布,准备压缩后的图像
$compressed_image = imagecreatetruecolor($new_width, $new_height);
// 将原图复制到新图像上,进行尺寸调整
imagecopyresampled($compressed_image, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// 保存压缩后的图像
imagejpeg($compressed_image, $outputPath, $compressionQuality); // 75 为压缩质量
// 清理内存
imagedestroy($image);
imagedestroy($compressed_image);
}
// 使用示例:压缩指定的图片并保存为新的路径
$inputPath = './data/attachment/common/cf/153611u6ybeumkkeaybkab.jpg'; // 输入文件路径
//记得带点.号,否则会被认为是linux的根路径从而被跨站目录限制
$outputPath = $inputPath; // 输出文件路径
$compressionQuality = 75; // 可选参数,默认75质量
compressImage($inputPath, $outputPath, $compressionQuality);
?>