上传压缩

This commit is contained in:
2026-01-15 17:02:40 +08:00
parent f98cf682ea
commit a2000127bc
+77 -7
View File
@@ -120,19 +120,38 @@ class UploadController
public function uploadImage(Request $request)
{
try {
$scene = $request->input('scene');
$file = $request->file('image');
$scene = trim((string)$request->input('scene', ''));
$sceneUrl = $scene ? $scene . '/' : '';
$file = $request->file('image');
if (!$file || !$file->isValid()) {
return $this->error('上传失败');
}
if (empty($scene)) {
// return $this->error('上传场景不能为空');
$sceneUrl = '';
}else{
$sceneUrl = $scene . '/';
// 允许的 MIME
$allowMime = [
'image/jpeg',
'image/png',
'image/webp',
];
$mime = $file->getMimeType();
if (!in_array($mime, $allowMime, true)) {
return $this->error('不支持的图片类型,支持jpeg、png、webp');
}
// 临时目录
$tmpDir = runtime_path('upload_tmp');
if (!is_dir($tmpDir)) {
mkdir($tmpDir, 0755, true);
}
$tmpPath = $tmpDir . '/' . uniqid('img_', true);
$file->move($tmpPath);
// 压缩处理
$finalPath = $this->compressImage($tmpPath, $mime);
$result = Storage::adapter('oss')
->path(config('oss.oss_main_dir') . $sceneUrl . date('Ymd'))
->size(1024*1024*30)
@@ -140,6 +159,12 @@ class UploadController
->extNo(['image/gif'])
->upload($file);
// 清理临时文件
@unlink($tmpPath);
if ($finalPath !== $tmpPath) {
@unlink($finalPath);
}
$ossservice = new OssService();
$data = [
@@ -162,6 +187,51 @@ class UploadController
}
}
protected function compressImage(string $srcPath, string $mime): string
{
// 不支持 imagick 直接返回原图
if (!extension_loaded('imagick')) {
return $srcPath;
}
try {
$image = new \Imagick();
$image->readImage($srcPath);
// 防止超大图
$maxWidth = 2000;
$maxHeight = 2000;
$image->thumbnailImage($maxWidth, $maxHeight, true);
// 自动方向修正(拍照图必备)
if (method_exists($image, 'autoOrient')) {
$image->autoOrient();
}
// PNG / JPEG → WebP
if (in_array($mime, ['image/png', 'image/jpeg'], true)) {
$image->setImageFormat('webp');
$image->setImageCompressionQuality(80);
$dstPath = $srcPath . '.webp';
$image->writeImage($dstPath);
} else {
// 其他类型直接原样
$dstPath = $srcPath;
}
$image->clear();
$image->destroy();
return $dstPath;
} catch (\Throwable $e) {
// 压缩失败直接返回原图
return $srcPath;
}
}
public function recordFileInfo($result, $request, $file, $scene, $category)
{
try {