php - 使用干预图像调整存储文件夹中的图像大小
问题描述
我的 Laravel 应用程序中有一个功能,允许用户将个人资料图片上传到他们的个人资料。
这是方法:
/**
* Store a user's profile picture
*
* @param Request $request
* @return void
*/
public function storeProfilePicture(User $user = null, Request $request)
{
$user = $user ?? auth()->user();
//Retrieve all files
$file = $request->file('file');
//Retrieve the file paths where the files should be moved in to.
$file_path = "images/profile-pictures/" . $user->username;
//Get the file extension
$file_extension = $file->getClientOriginalExtension();
//Generate a random file name
$file_name = Str::random(16) . "." . $file_extension;
//Delete existing pictures from the user's profile picture folder
Storage::disk('public')->deleteDirectory($file_path);
//Move image to the correct path
$path = Storage::disk('public')->putFile($file_path, $file);
// Resize the profile picture
$thumbnail = Image::make($path)->resize(50, 50, function ($constraint) {
$constraint->aspectRatio();
});
$thumbnail->save();
$user->profile()->update([
'display_picture' => Storage::url($path)
]);
return response()->json(['success' => $file_name]);
}
我正在尝试使用干预图像库来调整存储文件夹中上传的图片的大小,但我总是遇到同样的错误。
"Image source not readable", exception: "Intervention\Image\Exception\NotReadableException"
我也尝试Storage::url($path)
过storage_path($path)
解决方案
下面的代码与存储路径配合得很好,您可以直接从请求中制作拇指图像并将其放在任何地方作为所需路径,如下所示。请注意,这里我没有删除预先存储的文件或目录,因为我假设已经完成了。
$file = $request->file('file');
$path = "public/images/profile-pictures/{$user->username}/";
$file_extension = $file->getClientOriginalExtension();
$file_name = time(). "." . $file_extension;
// Resize the profile picture
$thumbnail = Image::make($file)->resize(50, 50)->encode($file_ext);
$is_uploaded = Storage::put( $path .$file_name , (string)$thumbnail ); // returns true if file uploaded
if($is_uploaded){
$user->profile()->update([
'display_picture'=> $path .$file_name
]);
return response()->json(['success' => $file_name]);
}
快乐编码
推荐阅读
- google-cloud-platform - kubernetes 仪表板:square/go-jose:密码原语中的错误
- r - 绘制仅知道开始时间/日期和采样周期的时间序列
- jquery - Bootstrap响应式导航按钮不起作用
- vba - Excel VBA 中的应用程序或对象定义错误
- python - 虚拟环境 pip 指向旧版本
- php - 在连接表上合并结果
- javascript - 以角度 4/5 加载外部 javascript 和 html
- python - 有没有办法在 numpy 中创建列向量而不必创建列表列表?
- java - 有效地搜索连续日期期间的列表
- php - 当产品属性有附加价格时更改产品价格(WooCommerce)