use app\common\model\Attachment;
public function index()
{
// 查询文件大小超过100万字节的attachment记录
$attachments = Attachment::where('filesize', '>', 1000000)->limit(100)->order('id desc')->select();
// 统计处理结果
$successCount = 0; // 成功计数
$failureCount = 0; // 失败计数
// 遍历attachment记录
foreach ($attachments as $attachment) {
// 调用压缩并更新数据库信息的函数
$success = $this->compressImageAndUpdateDatabase($attachment);
if ($success) {
$successCount++;
} else {
$failureCount++;
}
}
// 输出统计结果
echo "成功压缩并更新的文件数量:" . $successCount . PHP_EOL;
echo "压缩并更新失败的文件数量:" . $failureCount . PHP_EOL;
}
/**
* 压缩图片尺寸并更新数据库
* @param Attachment $attachment 要处理的数据库记录对象
* @param int $maxWidth 最大宽度
* @param int $maxHeight 最大高度
* @return bool 是否成功压缩图片并更新数据库
*/
function compressImageAndUpdateDatabase($attachment, $maxWidth = 1000, $maxHeight = 800)
{
$sourceFile = ROOT_PATH . 'public' . $attachment->url;
$info = getimagesize($sourceFile);
$mime = $info['mime'];
switch ($mime) {
case 'image/jpeg':
$image = imagecreatefromjpeg($sourceFile);
break;
case 'image/png':
$image = imagecreatefrompng($sourceFile);
break;
case 'image/gif':
$image = imagecreatefromgif($sourceFile);
break;
default:
return false; // 不支持的文件类型,压缩失败
}
$width = imagesx($image);
$height = imagesy($image);
$newWidth = $width;
$newHeight = $height;
if ($width > $maxWidth) {
$ratio = $maxWidth / $width;
$newWidth = $maxWidth;
$newHeight = $height * $ratio;
}
if ($newHeight > $maxHeight) {
$ratio = $maxHeight / $newHeight;
$newHeight = $maxHeight;
$newWidth = $newWidth * $ratio;
}
$newImage = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
// 保存压缩后的图片到原路径
switch ($mime) {
case 'image/jpeg':
$success = imagejpeg($newImage, $sourceFile, 80); // 80 是压缩质量,范围从 0(最差质量,最高压缩)到 100(最佳质量,无压缩)
break;
case 'image/png':
$success = imagepng($newImage, $sourceFile, 9); // 9 是压缩级别,范围从 0(无压缩)到 9(最高压缩)
break;
case 'image/gif':
$success = imagegif($newImage, $sourceFile);
break;
}
imagedestroy($image);
imagedestroy($newImage);
if ($success) {
// 更新数据库中的图片信息
$attachment->filesize = filesize($sourceFile);
$attachment->imagewidth = $newWidth;
$attachment->imageheight = $newHeight;
$attachment->imagetype = $mime;
$attachment->save();
return true;
} else {
return false; // 压缩失败
}
}