Yii框架实现图片上传的方法详解


Posted in PHP onMay 20, 2017

本文实例讲述了Yii框架实现图片上传的方法。分享给大家供大家参考,具体如下:

今天在网上看了下有关图片上传的教程,历经挫折才调试好,现在把相关代码及其说明贴出来,以供初次使用的朋友们参考。

Model:

<?php
class Upload extends CActiveRecord {
  public $image;
  public static function model($className = __CLASS__) {
    return $className;
  }
  public function tableName() {
    return '{{resource}}';
  }
  public function rules() {
    return array(
      array('image', 'file', 'types'=>'jpg, gif, png')
    );
  }
}

注:resource为数据表,表前缀可在main.php内设置,相信朋友们在看到文件上传时应该熟悉了main.php位置在哪及运作机制。

Controller:

<?php
class UploadController extends Controller {
  public function actionIndex() {
    $model=new Upload;
    if(isset($_POST['Upload'])) {
      $model->image=CUploadedFile::getInstance($model,'image');
      $ext = $model->image->getExtensionName();
      $fileName = uniqid() . '.' . $ext;
      $model->image->saveAs('assets/' . $fileName);
    }
    $this->renderPartial('index', array('model'=>$model));
  }
}

注:saveAs里面是存放图片上传后的地址,追踪下代码可以发现,该参数是move_uploaded_file函数的第二个参数,一定得是文件名。

View:

<meta charset="utf-8">
<?php echo CHtml::form(SITE_URL . 'admin/upload/index','post',array('enctype'=>'multipart/form-data')); ?>
<?php echo CHtml::activeFileField($model, 'image'); ?>
<?php echo CHtml::submitButton('提交');?>
<?php echo CHtml::endForm(); ?>

注:上面的SITE_URL为项目定义的常量,也就是项目的网址

相信经过上述步骤,朋友们应该可以上传成功图片,而且在项目下的assets目录下找到上传的图片。因为发现yii没有缩略图的方法,于是把thinkphp缩略图的方法整合了进来,把下面代码保存为Image.php放在项目下的protected/extensions目录下

<?php
class Image extends CController {
  /**
   +----------------------------------------------------------
   * 取得图像信息
   *
   +----------------------------------------------------------
   * @static
   * @access public
   +----------------------------------------------------------
   * @param string $image 图像文件名
   +----------------------------------------------------------
   * @return mixed
   +----------------------------------------------------------
   */
  static function getImageInfo($img) {
    $imageInfo = getimagesize($img);
    if ($imageInfo !== false) {
      $imageType = strtolower(substr(image_type_to_extension($imageInfo[2]), 1));
      $imageSize = filesize($img);
      $info = array(
        "width" => $imageInfo[0],
        "height" => $imageInfo[1],
        "type" => $imageType,
        "size" => $imageSize,
        "mime" => $imageInfo['mime']
      );
      return $info;
    } else {
      return false;
    }
  }
  /**
   +----------------------------------------------------------
   * 生成缩略图
   +----------------------------------------------------------
   * @static
   * @access public
   +----------------------------------------------------------
   * @param string $image 原图
   * @param string $type 图像格式
   * @param string $thumbname 缩略图文件名
   * @param string $maxWidth 宽度
   * @param string $maxHeight 高度
   * @param string $position 缩略图保存目录
   * @param boolean $interlace 启用隔行扫描
   +----------------------------------------------------------
   * @return void
   +----------------------------------------------------------
   */
  static function thumb($image, $thumbname, $type='', $maxWidth=200, $maxHeight=50, $interlace=true) {
    // 获取原图信息
    $info = Image::getImageInfo($image);
    if ($info !== false) {
      $srcWidth = $info['width'];
      $srcHeight = $info['height'];
      $type = empty($type) ? $info['type'] : $type;
      $type = strtolower($type);
      $interlace = $interlace ? 1 : 0;
      unset($info);
      $scale = min($maxWidth / $srcWidth, $maxHeight / $srcHeight); // 计算缩放比例
      if ($scale >= 1) {
        // 超过原图大小不再缩略
        $width = $srcWidth;
        $height = $srcHeight;
      } else {
        // 缩略图尺寸
        $width = (int) ($srcWidth * $scale);
        $height = (int) ($srcHeight * $scale);
      }
      // 载入原图
      $createFun = 'ImageCreateFrom' . ($type == 'jpg' ? 'jpeg' : $type);
      if(!function_exists($createFun)) {
        return false;
      }
      $srcImg = $createFun($image);
      //创建缩略图
      if ($type != 'gif' && function_exists('imagecreatetruecolor'))
        $thumbImg = imagecreatetruecolor($width, $height);
      else
        $thumbImg = imagecreate($width, $height);
       //png和gif的透明处理 by luofei614
      if('png'==$type){
        imagealphablending($thumbImg, false);//取消默认的混色模式(为解决阴影为绿色的问题)
        imagesavealpha($thumbImg,true);//设定保存完整的 alpha 通道信息(为解决阴影为绿色的问题)
      }elseif('gif'==$type){
        $trnprt_indx = imagecolortransparent($srcImg);
         if ($trnprt_indx >= 0) {
            //its transparent
            $trnprt_color = imagecolorsforindex($srcImg , $trnprt_indx);
            $trnprt_indx = imagecolorallocate($thumbImg, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
            imagefill($thumbImg, 0, 0, $trnprt_indx);
            imagecolortransparent($thumbImg, $trnprt_indx);
       }
      }
      // 复制图片
      if (function_exists("ImageCopyResampled"))
        imagecopyresampled($thumbImg, $srcImg, 0, 0, 0, 0, $width, $height, $srcWidth, $srcHeight);
      else
        imagecopyresized($thumbImg, $srcImg, 0, 0, 0, 0, $width, $height, $srcWidth, $srcHeight);
      // 对jpeg图形设置隔行扫描
      if ('jpg' == $type || 'jpeg' == $type)
        imageinterlace($thumbImg, $interlace);
      // 生成图片
      $imageFun = 'image' . ($type == 'jpg' ? 'jpeg' : $type);
      $imageFun($thumbImg, $thumbname);
      imagedestroy($thumbImg);
      imagedestroy($srcImg);
      return $thumbname;
    }
    return false;
  }
}
?>

再在项目下的protected/config/main.php中import字段加上

// autoloading model and component classes
  'import'=>array(
    'application.models.*',
    'application.components.*',
    'application.extensions.*',  #加上此行,意思为自动载入
  ),

再上面的Controller加上

public function actionIndex() {
    $model=new Upload;
    if(isset($_POST['Upload'])) {
      $model->image=CUploadedFile::getInstance($model,'image');
      $ext = $model->image->getExtensionName();
      $fileName = uniqid() . '.' . $ext;
      $model->image->saveAs('assets/' . $fileName);
      // 生成缩略图
      Image::thumb('assets/' . $fileName, 'assets/' . uniqid() . '.' . $ext);
    }
    $this->renderPartial('index', array('model'=>$model));
}

这次就完整了。

希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。

PHP 相关文章推荐
cmd下运行php脚本
Nov 25 PHP
PHP 用数组降低程序的时间复杂度
Dec 04 PHP
PHP SEO优化之URL优化方法
Apr 21 PHP
PHP url 加密解密函数代码
Aug 26 PHP
PHP 基于文件头的文件类型验证类函数
May 01 PHP
ThinkPHP实例化模型的四种方法概述
Aug 22 PHP
LINUX下PHP程序实现WORD文件转化为PDF文件的方法
May 13 PHP
浅谈PHP中关于foreach使用引用变量的坑
Nov 14 PHP
PHP实现的装箱算法示例
Jun 23 PHP
Laravel-添加后台模板AdminLte的实现方法
Oct 08 PHP
详解no input file specified 三种解决方法
Nov 29 PHP
关于PHP5.6+版本“No input file specified”问题的解决
Dec 11 PHP
Yii框架分页实现方法详解
May 20 #PHP
thinkPHP显示不出验证码的原因与解决方法分析
May 20 #PHP
yii2项目实战之restful api授权验证详解
May 20 #PHP
ThinkPHP下表单令牌错误与解决方法分析
May 20 #PHP
PHP那些琐碎的知识点(整理)
May 20 #PHP
PHP使用xpath解析XML的方法详解
May 20 #PHP
PHP CodeIgniter分页实例及多条件查询解决方案(推荐)
May 20 #PHP
You might like
博士208HAF收音机实习报告
2021/03/02 无线电
用php+javascript实现二级级联菜单的制作
2008/05/06 PHP
PHP 删除文件与文件夹操作 unlink()与rmdir()这两个函数的使用
2011/07/17 PHP
php使用多个进程同时控制文件读写示例
2014/02/28 PHP
使用YUI+Ant 实现JS CSS压缩
2014/09/02 PHP
PHP实现返回JSON和XML的类分享
2015/01/28 PHP
fckeditor上传文件按日期存放及重命名方法
2015/05/22 PHP
PHP register_shutdown_function()函数的使用示例
2015/06/23 PHP
Zend Framework教程之Zend_Controller_Plugin插件用法详解
2016/03/07 PHP
PHP CURL采集百度搜寻结果图片不显示问题的解决方法
2017/02/03 PHP
php实现的中文分词类完整实例
2017/02/06 PHP
JS解析json数据并将json字符串转化为数组的实现方法
2012/12/25 Javascript
jQuery实现精美的多级下拉菜单特效
2015/03/14 Javascript
node.js回调函数之阻塞调用与非阻塞调用
2015/11/13 Javascript
JavaScript对象数组如何按指定属性和排序方向进行排序
2016/06/15 Javascript
JS 拦截全局ajax请求实例解析
2016/11/29 Javascript
ES6 Promise对象概念与用法分析
2017/04/01 Javascript
Node.js 使用命令行工具检查更新
2017/06/08 Javascript
对vue中methods互相调用的方法详解
2018/08/30 Javascript
vuex提交state&amp;&amp;实时监听state数据的改变方法
2018/09/16 Javascript
JavaScript判断对象和数组的两种方法
2019/05/31 Javascript
js实现验证码干扰(静态)
2021/02/22 Javascript
Python正则表达式知识汇总
2017/09/22 Python
python对接ihuyi实现短信验证码发送
2020/05/10 Python
Python内置异常类型全面汇总
2020/05/28 Python
python使用多线程+socket实现端口扫描
2020/05/28 Python
美国在线购买和出售礼品卡网站:EJ Gift Cards
2019/06/09 全球购物
学生党员的自我评价范文
2014/03/01 职场文书
新闻发布会主持词
2014/03/28 职场文书
我的中国梦演讲稿1000字
2014/08/19 职场文书
身边的榜样活动方案
2014/08/20 职场文书
2014年祖国生日寄语
2014/09/19 职场文书
2015年妇联工作总结范文
2015/04/22 职场文书
贷款收入证明范本
2015/06/12 职场文书
正能量励志演讲稿三分钟(范文)
2019/07/11 职场文书
导游词之贵州织金洞
2019/10/12 职场文书