thinkphp5 upload image and generate thumbnail method

小云云
Release: 2023-03-19 06:52:02
Original
1842 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

相关推荐:

AJAX实现图片预览与上传及生成缩略图的方法

PHP生成PSD文件缩略图教程

纯css实现缩略图悬停效果实例教程

The above is the detailed content of thinkphp5 upload image and generate thumbnail method. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!