3

我正在尝试使用 Laravel Nova 管理面板和 api 创建图像/用户头像。我需要为每次下载生成 3 张图片 - 头像、缩略图和预览。

 public function fields(Request $request)
     {
          return [

       //some fields else
        Avatar::make(__('Profile Photo'), 'avatar_path')
             ->path('images/users/avatars')
             ->storeAs(function (Request $request){
                 $file = $request->file('avatar_path');
                 return $request->user()->id.'_'. sha1($file->getClientOriginalName()).'.'.$file->getClientOriginalExtension();
             })
            ->preview(function ($value, $disk){
                 return $this->getCroppedAvatar($value, 'prev', 636);
             })
             ->thumbnail(function ($value, $disk){
                 return $this->getCroppedAvatar($value, 'thumb', 64);
             })
             ->disableDownload(),

在这个领域我使用以下方法

     public static function getCroppedAvatar($value, $type, $size)
         {
              $path = str_replace('avatars', $type , $value);
              if ($value && !Storage::exists($value)) {
                  return null;
              }
              if ($value && is_file(Storage::path($path)) && !is_dir(Storage::path($path))) {
             return Storage::url($path);
              }
              if ($value) {
                 Image::make(Storage::path($value))
                   ->widen($size)->save(Storage::path($path));
                  Log::info('New preview is ' . Storage::path($path));
                  return Storage::url($path);
              }
              return null;
          }

在这种情况下,Laravel Nova 正在工作,但如果我尝试从 API 控制器调用 getCroppedAvatar,我会在 Image::make 行出现错误:

Unsupported image type. GD driver is only able to decode JPG, PNG, GIF or WebP files. {"userId":16,"exception":"[object] (Intervention\\Image\\Exception\\NotReadableException(code: 0): Unsupported image type. GD driver is only able to decode JPG, PNG, GIF or WebP files. at /var/www/tracker/vendor/intervention/image/src/Intervention/Image/Gd/Decoder.php:59)

API 控制器上的代码

    Storage::put($fileDirectory.'/'.$fileName, $image);
    User::getCroppedAvatar($fileDirectory.'/'.$fileName,'prev', 636);
    User::getCroppedAvatar($fileDirectory.'/'.$fileName,'thumb', 64);

在这两种情况下,我都使用 png 和 jpg 文件。参数值相同。我该如何解决?谢谢!

4

1 回答 1

1

最后,我找到了解决方案。据我了解,存储类创建的图像类型不正确,所以我从 API Controller 更改了这一行

Storage::put($fileDirectory.'/'.$fileName, $image);

为了这:

Image::make($file)->save(Storage::path($filePath));
于 2019-09-19T14:19:03.617 回答