Home > Backend Development > PHP Tutorial > thinkphp5 public methods for uploading images and generating thumbnails

thinkphp5 public methods for uploading images and generating thumbnails

jacklove
Release: 2023-04-02 10:30:01
Original
2099 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

以上这篇thinkphp5上传图片及生成缩略图公共方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持php中文网。

您可能感兴趣的文章:

微信小程序之支付后调用SDK的异步通知及验证处理订单方法的详解

PHP 使用Echarts生成数据统计报表的实现

PHP根据手机号判断运营商

The above is the detailed content of thinkphp5 public methods for uploading images and generating thumbnails. 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