使用Unisharp Laravel处理文件上传和调整图像大小



我的laravel项目使用Unisharp文件上传。包装工作正常。现在我想要的是,我想要一个文件类型的数组,比如:

[name] => MyFile.jpg      
[type] => image/jpeg
[tmp_name] => /tmp/php/php6hst32
[error] => UPLOAD_ERR_OK
[size] => 98174

Unisharp文件管理器的图像URL。假设我从Unisharp文件管理器中选择http://example.com/storage/files/42/lace-up.png,我想得到如上所述的文件数组。

我想要这个,因为我想相应地调整图像的大小,并将它们存储到不同的文件夹中。

我创建了以下功能来上传和调整图像大小:

function uploadImage($file, $dir, $thumb_dimension=null){
$path = public_path().'/uploads/'.$dir;
if(!File::exists($path)){
File::makeDirectory($path, 0777, true, true);
}
$file_name = ucfirst($dir).'-'.date('Ymdhis').rand(0,999).".".$file->getClientOriginalExtension();
$success = $file->move($path, $file_name);
if($success){
$file_path = $path.'/'.$file_name;
if($thumb_dimension){
list($width,$height) = explode('x',$thumb_dimension);
Image::make($file_path)->resize($width,$height, function($const){
$const->aspectRatio();
})->save($path.'/Thumb-'.$file_name);
}
return $file_name;
} else {
return null;
}
}

有可能吗?

编辑

我想在获得图像的详细信息后使用以下功能。

function uploadImage($file, $dir, $thumb_dimension=null){
$path = public_path().'/uploads/'.$dir;
if(!File::exists($path)){
File::makeDirectory($path, 0777, true, true);
}

$file_name = ucfirst($dir).'-'.date('Ymdhis').rand(0,999).".".$file->getClientOriginalExtension();
$success = $file->move($path, $file_name);
if($success){
$file_path = $path.'/'.$file_name;
if($thumb_dimension){
list($width,$height) = explode('x',$thumb_dimension);
Image::make($file_path)->resize($width,$height, function($const){
$const->aspectRatio();
})->save($path.'/Thumb-'.$file_name);
}
return $file_name;
} else {
return null;
}
}

如果你只想从链接中提取图像,你只需要创建一个小函数来处理它。

public function getImageViaLink($link){
try {
$info = pathinfo($link);
$image = file_get_contents($link);
$arr['basename'] = $info['basename'];
$file_info = new finfo(FILEINFO_MIME_TYPE);
$mime_type = $file_info->buffer($image);
$arr['size'] = strlen($image);
$arr['mime_type'] = $mime_type;
$path = public_path() .'/'. $arr['basename'];

// You can save contents of link in your file directly or store it in tmp
file_put_contents($path, $image);
$arr['path'] = $path;
return $arr;
}
catch (Exception $e) {
echo $e->getMessage();
}

}

至于数组中error的情况,您基本上想要文件上传错误,但Exception可以很容易地处理它。

附带说明一下,如果在使用unisharp存储图像时有请求变量,则可以在$request中访问所有这些详细信息。

// dd() of a request containing image file.
array:2 [▼
"_token" => "e7v7ZxaKoIFGIYOscCAFwsoB8olw8lrNjwx8Azyi"
"attachment_1_0" => UploadedFile {#229 ▼
-test: false
-originalName: "db.png"
-mimeType: "image/png"
-size: 86110
-error: 0
path: "C:xampptmp"
filename: "phpF4F4.tmp"
basename: "phpF4F4.tmp"
pathname: "C:xampptmpphpF4F4.tmp"
extension: "tmp"
realPath: "C:xampptmpphpF4F4.tmp" 

... and many more

您可以创建一个侦听器,每当存储图像时,您都可以创建另一个包含所有详细信息的副本,将其保存到另一个位置。

最新更新