Laravel8实现上传图片裁剪功能方法

2021-07-26   阅读:2109   分类:后端    标签: Laravel

Laravel8实现上传图片裁剪功能方法

1、 安装扩展

composer require intervention/image

2、 在 app/config/app.php 添加 providers 数组中添加如下代码:

Intervention\Image\ImageServiceProvider::class,

3、 在 app/config/app.php 添加 aliases 数组中添加如下代码:

'Image' => Intervention\Image\Facades\Image::class,

4、发布扩展生成 config/image.php 配置文件,执行下面命令

php artisan vendor:publish --provider="Intervention\Image\ImageServiceProviderLaravelRecent"

5、使用

<?php
use Intervention\Image\Facades\Image;
//后面为图片路径
$img = Image::make('./image/abc.jpg')->resize(300, 300);
// 将处理后的图片重新保存到其他路径
$img->save('./image/new_abc.jpg');
?>

完整方法:

 <?php
  /*
          * 图片上传接口
          * 文件名
          * 文件夹名
          * */
    public static function uploadImg($file,$folder){
        $tmp = $file;
        $folder = $folder ? $folder : "";
        $path = '/static/uploads'; //public下的Uploads
        if ($tmp->isValid()) { //判断文件上传是否有效
            $FileType = $tmp->getClientOriginalExtension(); //获取文件后缀
 
            $FilePath = $tmp->getRealPath(); //获取文件临时存放位置
 
            $FileName = $folder.'/'.date('Ymd').'/' . uniqid() . '.' . $FileType; //定义文件名
 
            Storage::disk('Uploads')->put($FileName, file_get_contents($FilePath)); //存储文件
            $img = Image::make(public_path().$path . '/' . $FileName)->resize(30, 30);
            $img->save(public_path().$path . '/' . $FileName);
            return $data = [
                'code' => ApiErrDesc::UPLOAD_SUCCESS[0],
                'msg' =>ApiErrDesc::UPLOAD_SUCCESS[1] ,
                'data'=>['path' => $path . '/' . $FileName] //文件路径
            ];
        }else{
            return $data = [
                'code' => ApiErrDesc::UPLOAD_ERROR[0],
                'msg' =>ApiErrDesc::UPLOAD_ERROR[1] ,
                'data'=>[]
            ];
        }
    }
?>


【腾讯云】 爆款2核2G3M云服务器首年 61元,2核2G4M云服务器新老同享 99元/年,续费同价

‘简忆博客’微信公众号 扫码关注‘简忆博客’微信公众号,获取最新文章动态
转载:请说明文章出处“来源简忆博客”。http://tpxhm.com/adetail/748.html

×
觉得文章有用就打赏一下文章作者
微信扫一扫打赏 微信扫一扫打赏
支付宝扫一扫打赏 支付宝扫一扫打赏

文章评论(0)

登录
简忆博客壁纸一
简忆博客壁纸二
简忆博客壁纸三
简忆博客壁纸四
简忆博客壁纸五
简忆博客壁纸六
简忆博客壁纸七
简忆博客壁纸八
头像

简忆博客
勤于学习,乐于分享

置顶推荐

打赏本站

如果你觉得本站很棒,可以通过扫码支付打赏哦!
微信扫码:你说多少就多少~
微信扫码
支付宝扫码:你说多少就多少~
支付宝扫码
×