我有这个代码上传头像:
if(request()->file("avatar_upload")) {
$file = request()->file("avatar_upload");
$ext = $file->guessClientExtension();
if($ext == "jpg" || $ext == "jpeg"){
$file->storeAs('public/avatars/' . Auth::user()->id , "avatar.jpg");
}
if($ext == "png"){
$file->storeAs('public/avatars/' . Auth::user()->id , "avatar.png");
$imageobject = imagecreatefrompng('public/avatars/' . Auth::user()->id . "/avatar.png");
imagejpeg($imageobject, "avatar.jpg");
}
}
然而,函数imagecreatefrompng
永远找不到上传的头像(我使用sylinks)
我试过了:
$imageobject = imagecreatefrompng('public/avatars/' . Auth::user()->id . "/avatar.png")
这给了我这个错误:
imagecreatefrompng(public/avatars/1/avatar.png): failed to open stream: No such file or directory
并尝试了这个:
$imageobject = imagecreatefrompng('storage/avatars/' . Auth::user()->id . "/avatar.png");
哪个不给我任何错误,但什么都不做
答案 0 :(得分:3)
试试这个。使用laravel核心函数获取公用文件夹的路径。还要确保要保存文件的目录必须具有设置为0777的权限。
if(request()->file("avatar_upload")) {
$file = request()->file("avatar_upload");
$ext = $file->guessClientExtension();
if($ext == "jpg" || $ext == "jpeg"){
$file->storeAs('public/avatars/' . Auth::user()->id , "avatar.jpg");
}
if($ext == "png"){
$imageName = $file->getClientOriginalExtension();
$file->move(public_path().'/avatars/'.Auth::user()->id,$imageName);
$imageobject = imagecreatefrompng(public_path().'/avatars/'.Auth::user()->id. '/avatar.png');
//-----------------------------------------------------------^^^^^^----here
imagejpeg($imageobject, 'avatar.jpg',100);
remove old image
imagedestroy($imageobject);
}
}
答案 1 :(得分:1)
根据你的意见,如果是sym链接,那么它应该是这样的
$imageobject = imagecreatefrompng(storage_path('app/public/avatars/' . Auth::user()->id . "/avatar.png"));
imagejpeg($imageobject, "avatar.jpg");
答案 2 :(得分:0)
if(request()->file("avatar_upload")) {
$file = request()->file("avatar_upload");
$ext = $file->guessClientExtension();
if($ext == "jpg" || $ext == "jpeg" || $ext == "png"){
$file->storeAs('public/avatars/' . Auth::user()->id , "avatar.jpg");
}
}
无需分离png和jpeg。您也可以简单地将avatar.jpg存储为图像本身。