Home > Backend Development > PHP Tutorial > How to upload images and generate thumbnails in thinkphp5

How to upload images and generate thumbnails in thinkphp5

不言
Release: 2023-03-30 17:34:02
Original
2671 people have browsed it

下面为大家分享一篇thinkphp5上传图片及生成缩略图公共方法,具有很好的参考价值,希望对大家有所帮助。

直接上代码,可以写在公共文件common和继承的基础类中,方便调用

/*
   * $name为表单上传的name值
   * $filePath为为保存在入口文件夹public下面uploads/下面的文件夹名称,没有的话会自动创建
   * $width指定缩略宽度
   * $height指定缩略高度
   * 自动生成的缩略图保存在$filePath文件夹下面的thumb文件夹里,自动创建
   * @return array 一个是图片路径,一个是缩略图路径,如下:
   * array(2) {
     ["img"] => string(57) "uploads/img/20171211\3d4ca4098a8fb0f90e5f53fd7cd71535.jpg"
     ["thumb_img"] => string(63) "uploads/img/thumb/20171211/3d4ca4098a8fb0f90e5f53fd7cd71535.jpg"
    }
   */
  protected function uploadFile($name,$filePath,$width,$height)
  {
    $file = request()->file($name);
    if($file){
      $filePaths = ROOT_PATH . 'public' . DS . 'uploads' . DS .$filePath;
      if(!file_exists($filePaths)){
        mkdir($filePaths,0777,true);
      }
      $info = $file->move($filePaths);
      if($info){
        $imgpath = 'uploads/'.$filePath.'/'.$info->getSaveName();
        $image = \think\Image::open($imgpath);
        $date_path = 'uploads/'.$filePath.'/thumb/'.date('Ymd');
        if(!file_exists($date_path)){
          mkdir($date_path,0777,true);
        }
        $thumb_path = $date_path.'/'.$info->getFilename();
        $image->thumb($width, $height)->save($thumb_path);
        $data['img'] = $imgpath;
        $data['thumb_img'] = $thumb_path;
        return $data;
      }else{
        // 上传失败获取错误信息
        return $file->getError();
      }
    }
  }
Copy after login

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

thinkphp3.2.0中setInc方法的源码分析

thinkPHP5.0框架配置格式、加载解析与读取的方法

ThinkPHP实现转换数据库查询结果数据到对应类型

The above is the detailed content of How to upload images and generate thumbnails in thinkphp5. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template