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 相关文章推荐
dedecms采集中可以过滤多行代码的正则表达式
Mar 17 PHP
php 代码优化的42条建议 推荐
Sep 25 PHP
PHP得到mssql的存储过程的输出参数功能实现
Nov 23 PHP
php ImageMagick windows下安装教程
Jan 26 PHP
PHP网站开发中常用的8个小技巧
Feb 13 PHP
php中动态调用函数的方法
Mar 16 PHP
PHP使用mkdir创建多级目录的方法
Dec 22 PHP
laravel学习教程之关联模型
Jul 30 PHP
php使用file函数、fseek函数读取大文件效率对比分析
Nov 04 PHP
PHP实现动态创建XML文档的方法
Mar 30 PHP
PHP实现唤起微信支付功能
Feb 18 PHP
PHP中Session ID的实现原理实例分析
Aug 17 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
咖啡的种类和口感
2021/03/03 新手入门
PHP imagegrabscreen和imagegrabwindow(截取网站缩略图)的实例代码
2013/11/07 PHP
PHP生成图片缩略图类示例
2017/01/12 PHP
Yii 2.0自带的验证码使用经验分享
2017/06/19 PHP
php合并数组并保留键值的实现方法
2018/03/12 PHP
[对联广告] JS脚本类
2006/08/27 Javascript
关于文本框的一些限制控制总结~~
2010/04/15 Javascript
AJAX分页的代码(后台asp.net)
2011/02/14 Javascript
jQuery创建平滑的页面滚动(顶部或底部)
2013/02/26 Javascript
利用毫秒减值计算时长的js代码
2013/09/22 Javascript
javascript中的=等号个数问题两个跟三个有什么区别
2013/10/23 Javascript
通过实例理解javascript中没有函数重载的概念
2015/06/03 Javascript
基于Jquery代码实现手风琴菜单
2015/11/19 Javascript
javascript实现随机显示星星特效
2016/01/28 Javascript
nodejs结合Socket.IO实现的即时通讯功能详解
2018/01/12 NodeJs
解决在Bootstrap模糊框中使用WebUploader的问题
2018/03/22 Javascript
官方推荐react-navigation的具体使用详解
2018/05/08 Javascript
使用weixin-java-tools完成微信授权登录、微信支付的示例
2018/09/26 Javascript
Vue组件间通信方法总结(父子组件、兄弟组件及祖先后代组件间)
2019/04/17 Javascript
Vue实现仿iPhone悬浮球的示例代码
2020/03/13 Javascript
vue自定义插件封装,实现简易的elementUi的Message和MessageBox的示例
2020/11/20 Vue.js
Python多进程并发(multiprocessing)用法实例详解
2015/06/02 Python
Scrapy爬虫实例讲解_校花网
2017/10/23 Python
Python selenium实现微博自动登录的示例代码
2018/05/16 Python
tensorflow 用矩阵运算替换for循环 用tf.tile而不写for的方法
2018/07/27 Python
在python3中使用shuffle函数要注意的地方
2020/02/28 Python
html5 div布局与table布局详解
2016/11/16 HTML / CSS
Agoda中文官网:安可达(低价预订全球酒店)
2021/01/18 全球购物
北京大学自荐信范文
2014/01/28 职场文书
会计师职业生涯规划范文
2014/02/18 职场文书
优秀教师演讲稿
2014/05/06 职场文书
上班迟到检讨书范文300字
2014/11/02 职场文书
六年级小学生评语
2014/12/26 职场文书
任命书格式模板
2015/09/22 职场文书
解析目标检测之IoU
2021/06/26 Python
集英社今正式宣布 成立游戏公司“集英社Games”
2022/03/31 其他游戏