php - 如何修复 Image::make 上不支持的图像类型的错误
问题描述
我正在尝试使用 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 文件。参数值相同。我该如何解决?谢谢!
解决方案
最后,我找到了解决方案。据我了解,存储类创建的图像类型不正确,所以我从 API Controller 更改了这一行
Storage::put($fileDirectory.'/'.$fileName, $image);
为了这:
Image::make($file)->save(Storage::path($filePath));
推荐阅读
- python - 如何使用 numpy 从 RGB 图像中删除折线
- javascript - .map 在使用 useState 钩子触发 setState 后不是函数
- reactjs - 状态变化正在重置导航
- ios - 如何使用新的 App 结构实现 SceneDelegate 的场景(_:willConnectTo:options:) 中存在的代码
- gradle - 仅从 gradle spring boot 项目中的 maven 依赖项中检索到 pom.xml
- javascript - React 组件的阶段和 React 组件的生命周期有什么区别?
- python - Django objects.get() 函数不起作用,但 objects.filter().first() 起作用
- java - 元素链接没有重定向到它的目标页面?
- gradle - 如何跟踪泄漏的 Gradle API 依赖项
- python - 尝试使用 pygame 制作游戏的 Python 新手