图像干预与 Laravel 5.4 存储

2022-08-30 13:18:15

我正在使用存储立面来存储一个工作正常的头像,但我想调整我的图像大小,就像我在以前版本的laravel中所做的那样。我该怎么做?这是我到目前为止所拥有的(不起作用)

  $path   = $request->file('createcommunityavatar');
  $resize = Image::make($path)->fit(300);
  $store  = Storage::putFile('public/image', $resize);
  $url    = Storage::url($store);

错误信息:

  Command (hashName) is not available for driver (Gd).

答案 1

您正在尝试将错误的对象传递到 putFile 中。该方法需要 File 对象(而不是图像)。

$path   = $request->file('createcommunityavatar');

// returns \Intervention\Image\Image - OK
$resize = Image::make($path)->fit(300);

// expects 2nd arg - \Illuminate\Http\UploadedFile - ERROR, because Image does not have hashName method
$store  = Storage::putFile('public/image', $resize);

$url    = Storage::url($store);

好了,现在当我们理解了主要原因后,让我们修复代码

// returns Intervention\Image\Image
$resize = Image::make($path)->fit(300)->encode('jpg');

// calculate md5 hash of encoded image
$hash = md5($resize->__toString());

// use hash as a name
$path = "images/{$hash}.jpg";

// save it locally to ~/public/images/{$hash}.jpg
$resize->save(public_path($path));

// $url = "/images/{$hash}.jpg"
$url = "/" . $path;

假设您要使用存储外观:

// does not work - Storage::putFile('public/image', $resize);

// Storage::put($path, $contents, $visibility = null)
Storage::put('public/image/myUniqueFileNameHere.jpg', $resize->__toString());

答案 2

put 方法与图像干预输出配合使用。putFile 方法接受 Illuminate\Http\File 或 Illuminate\Http\UploadFile 实例。

$photo = Image::make($request->file('photo'))
  ->resize(400, null, function ($constraint) { $constraint->aspectRatio(); } )
  ->encode('jpg',80);

Storage::disk('public')->put( 'photo.jpg', $photo);

上面的代码将上传的文件大小调整为400px宽度,同时保持宽高比。然后以 80% 的质量编码为 jpg。然后将该文件存储到公共光盘中。请注意,您必须提供文件名,而不仅仅是目录。


推荐