<?php
use Intervention\Image\ImageManagerStatic as Image;
class Util
{
public function imageProcessing($imagePath, $imageMode = '', $newImageName = '', $newImagePath = '')
{
try {
if (!$imagePath) return '';
$imageInfo = getimagesize($imagePath);
$width = $imageInfo['0'];
$height = $imageInfo['1'];
list($width, $ratio) = $this->imageRatio($width, $imageMode);
$newHeight = $width / $ratio;
if ($newHeight == $height) {
return $imagePath;
}
$pathTmp = explode('/', $imageInfo['mime']);
$suffix = '.' . ltrim(end($pathTmp), '.');
if (!$newImageName) {
$newImageName = uniqid() . $suffix;
}
if (!$newImagePath) {
$newImagePath = public_path() . '/upload_image/';
@mkdir($newImagePath, 0777, true);
}
$img = Image::make($imagePath)->resize($width, $newHeight);
$path = $newImagePath . $newImageName;
$img->save($path);
return $path;
} catch (\Exception $e) {
\Log::error('图片裁剪出错:' . $e->getMessage());
return $imagePath;
}
}
private function imageRatio($width, $imageMode = '')
{
$ratio = 1;
$min_width = $width;
$max_width = $width;
switch ($imageMode) {
case EnumList::IMAGE_MODE_LARGE:
$min_width = 600;
$max_width = 2400;
$ratio = 1.91;
break;
case EnumList::IMAGE_MODE_LARGE_VERTICAL:
$min_width = 187;
$max_width = 750;
$ratio = 0.62;
break;
case EnumList::IMAGE_MODE_BIG_ONE:
$min_width = 320;
$max_width = 1280;
break;
case EnumList::IMAGE_MODE_VIDEO:
$min_width = 1280;
$max_width = 2560;
$ratio = 1.78;
break;
case EnumList::IMAGE_MODE_VIDEO_SQUARE:
$min_width = 640;
$max_width = 1280;
break;
case EnumList::IMAGE_MODE_VIDEO_VERTICAL:
$min_width = 720;
$max_width = 1440;
$ratio = 0.56;
break;
}
if ($width > $max_width) {
$width = $max_width;
} else if ($width < $min_width) {
$width = $min_width;
}
return [$width, $ratio];
}
}