调整图像大小并存储到Laravel 7中的存储中

问题描述

到目前为止,我正在使用以下代码上传图片

if($request->hasFile('image')) {
  $path = $request->image->getClientOriginalName();
  $name = time() . '-' . $path;
  $news->image = $request->file('image')->storeAs('public/news',$name);
}

检查文件图像,将其恢复为原始名称,创建附加到图像文件名的时间格式,然后上传到所需文件夹中的存储中。

上传文件目录之前,如何调整图像的大小?

我已经阅读了Laravel 7中包含的干预方法,但是有人可以帮助我使用干预方法并结合我上传图像的逻辑吗?

我曾经这样尝试过:

use Intervention\Image\ImageManagerStatic as Image; // use Intervention
    
if($request->hasFile('image')) {
  $path = $request->image->getClientOriginalName();
  $resize = Image::make($path)->fit(300);
  $name = time() . '-' . $resize;
  $news->image = $request->file('image')->storeAs('public/news',$name);
}

但是我遇到Image source not readable错误

解决方法

显然,干预无法读取您的图像,请检查您提供的路径。

dd($path);

就我而言,这就是我的工作方式:

$img = Image::make('storage/'.$banner)->resize(800,250);

然后在上传图片之前调整图片大小,您可以这样做:

//$image is the temporary path of your image (/tmp/something)
$image = $request->image;

//Create a Image object with the tmp path
$resized_img = Image::make($image);

//Do what you want and save your modified image on the same temporary path as the original image.
$resized_img->fit(300)->save($image);

//Upload your image on your bucket and get the final path of your image
$path = $image->storeAs('public/news',$name)
,

经过长时间的测试,我找到了解决方案。这是下面的代码:

if($request->hasFile('image')) {
    $image = $request->file('image');
    $imageName = $image->getClientOriginalName();
    $fileName =  'public/news/' . time() . '-' . $imageName;
    Image::make($image)->resize(600,300)->save(storage_path('app/' . $fileName));
    $news->image = $fileName;
  }

主要问题是路径,我也不需要使用storeAs()函数,只需使用Intervention函数即可……仅此而已。 这种方法更加灵活,并且可以从出色的Intervention库中轻松实现其他功能。