Sfoglia il codice sorgente

图片上传优化

shish 6 anni fa
parent
commit
7b8addbaf0
1 ha cambiato i file con 22 aggiunte e 9 eliminazioni
  1. 22 9
      app/business/controllers/UploadController.php

+ 22 - 9
app/business/controllers/UploadController.php

@@ -33,23 +33,36 @@ class UploadController extends BaseController
 			}
 			$preFileName = stringUtil::uniqueFileName();
 			$newFile = $preFileName . ".{$type}";
-			$fullPath = $path . $newFile;
-			if (file_put_contents($fullPath, base64_decode(str_replace($result[1], '', $base64_image_content))) == false) {
+			$fullPathFile = $path . $newFile;
+			if (file_put_contents($fullPathFile, base64_decode(str_replace($result[1], '', $base64_image_content))) == false) {
 				util::fail('上传失败!!');
 			}
 			$img = "/uploads/{$merchantId}/{$month}/{$date}/" . $newFile;
-
-			$imgInfo = getimagesize($fullPath);
+			$imgInfo = getimagesize($fullPathFile);
 			$width = $imgInfo[0];
 			$height = $imgInfo[1];
-			if($width > 800){
 
+			//如果图片太大,进行压缩,并删除原图
+			if ($width > 800) {
+				$newWidth = 800;
+				$newHeight = ceil((800 * $height) / $width);
+				$preFileName = stringUtil::uniqueFileName();
+				$newFile = $preFileName . ".{$type}";
+				$newFullPathFile = $path . $newFile;
+				Image::thumbnail($fullPathFile, $newWidth, $newHeight)->save($newFullPathFile, ['quality' => 100]);
+				$width = $newWidth;
+				$height = $newHeight;
+				$img = "/uploads/{$merchantId}/{$month}/{$date}/" . $newFile;
+				unlink($fullPathFile);
+				$fullPathFile = $newFullPathFile;
 			}
-			
-			$new = $path.$preFileName.'_small.'.$type;
-			//压缩
-			Image::thumbnail($fullPath, 167, 111)->save($new, ['quality' => 100]);
 
+			//生成小图 200px
+			$smallWidth = 200;
+			$smallHeight = ceil((200 * $height) / $width);
+			$smallFullPathFile = $path . $preFileName . '_small.' . $type;
+			Image::thumbnail($fullPathFile, $smallWidth, $smallHeight)->save($smallFullPathFile, ['quality' => 100]);
+			
 			$data = business::formatUploadImg($img);
 			$data['shortUrl'] = $img;
 			util::success($data);