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 相关文章推荐
教你IIS6的PHP最佳配置方法
Sep 05 PHP
学习discuz php 引入文件的方法DISCUZ_ROOT
Jun 21 PHP
PHP用SAX解析XML的实现代码与问题分析
Aug 22 PHP
PHP判断变量是否为0的方法
Feb 08 PHP
PHP把JPEG图片转换成Progressive JPEG的方法
Jun 30 PHP
Laravel模板引擎Blade中section的一些标签的区别介绍
Feb 10 PHP
Yii 2.0自带的验证码使用经验分享
Jun 19 PHP
PHP设计模式之模板模式定义与用法详解
Dec 20 PHP
Laravel框架基于中间件实现禁止未登录用户访问页面功能示例
Jan 17 PHP
laravel通过a标签从视图向控制器实现传值
Oct 15 PHP
深入浅析安装PhpStorm并激活的步骤详解
Sep 17 PHP
phpstorm最新激活码分享亲测phpstorm2020.2.3版可用
Nov 22 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
php视频拍照上传头像功能实现代码分享
2015/10/08 PHP
PHP中SSO Cookie登录分析和实现
2015/11/06 PHP
PHP数组实例详解
2016/06/26 PHP
Yii实现的多级联动下拉菜单
2016/07/13 PHP
解决window.opener=null;window.close(),只支持IE6不支持IE7,IE8的问题
2014/01/14 Javascript
jQuery中的val()示例应用
2014/02/26 Javascript
jquery动态添加元素事件失效问题解决方法
2014/05/23 Javascript
如何通过js实现图片预览功能【附实例代码】
2016/03/30 Javascript
详解ECharts使用心得总结
2016/12/06 Javascript
初识NodeJS服务端开发入门(Express+MySQL)
2017/04/07 NodeJs
详解使用vue脚手架工具搭建vue-webpack项目
2017/05/10 Javascript
jQuery实现的简单前端搜索功能示例
2017/10/28 jQuery
vue的过滤器filter实例详解
2018/09/17 Javascript
Vue项目使用localStorage+Vuex保存用户登录信息
2019/05/27 Javascript
[02:20]2014DOTA2西雅图邀请赛 MVP外卡赛首胜采访
2014/07/09 DOTA
[01:02:46]VGJ.S vs NB 2018国际邀请赛小组赛BO2 第二场 8.18
2018/08/19 DOTA
在Docker上部署Python的Flask框架的教程
2015/04/08 Python
Python 性能优化技巧总结
2016/11/01 Python
python抓取文件夹的所有文件
2018/02/27 Python
使用matplotlib绘制图例标签中带有公式的图
2019/12/13 Python
Xadmin+rules实现多选行权限方式(级联效果)
2020/04/07 Python
Python爬虫入门有哪些基础知识点
2020/06/02 Python
Elasticsearch py客户端库安装及使用方法解析
2020/09/14 Python
CSS3 box-sizing属性
2009/04/17 HTML / CSS
Finishline官网:美国一家领先的运动品牌鞋类、服装零售商
2016/07/20 全球购物
美国在线咖啡、茶和餐厅供应商:LollicupStore
2018/05/04 全球购物
Footshop罗马尼亚:最好的运动鞋选择
2019/09/10 全球购物
大学在校生求职信范文
2013/11/21 职场文书
马云北大演讲完整版:真心话,什么才是阿里的核心竞争力?
2014/04/04 职场文书
2014年护士工作总结范文
2014/11/11 职场文书
给老婆的保证书
2015/01/16 职场文书
教师学习十八届五中全会精神心得体会
2016/01/05 职场文书
《鸡兔同笼》教学反思
2016/02/19 职场文书
《进击的巨人》新联动CM 兵长强势出击兽巨人
2022/04/05 日漫
MySQL中EXPLAIN语句及用法
2022/05/20 MySQL
WinServer2012搭建DNS服务器的方法步骤
2022/06/10 Servers