首页 > 解决方案 > 使用干预图像调整存储文件夹中的图像大小

问题描述

我的 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)

标签: phplaravelintervention

解决方案


下面的代码与存储路径配合得很好,您可以直接从请求中制作拇指图像并将其放在任何地方作为所需路径,如下所示。请注意,这里我没有删除预先存储的文件或目录,因为我假设已经完成了。

$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]);
}

快乐编码


推荐阅读