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 相关文章推荐
编译问题
Oct 09 PHP
利用PHP制作简单的内容采集器的代码
Nov 28 PHP
php eval函数用法总结
Oct 31 PHP
CodeIgniter图像处理类的深入解析
Jun 17 PHP
PHP中使用break跳出多重循环代码实例
Jan 21 PHP
WampServer搭建php环境时遇到的问题汇总
Jul 23 PHP
php生成图片验证码的实例讲解
Aug 03 PHP
求帮忙修改个php curl模拟post请求内容后并下载文件的解决思路
Sep 20 PHP
简述php环境搭建与配置
Dec 05 PHP
微信支付之JSAPI公众号支付详解
May 15 PHP
php自定义排序uasort函数示例【二维数组按指定键值排序】
Jun 19 PHP
PHP实现的多进程控制demo示例
Jul 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显示今天、今月、上月、今年的起点/终点时间戳的代码
2011/05/25 PHP
gd库图片下载类实现下载网页所有图片的php代码
2012/08/20 PHP
文本框输入时 实现自动提示(像百度、google一样)
2012/04/05 Javascript
jQuery学习笔记 操作jQuery对象 CSS处理
2012/09/19 Javascript
JS在textarea光标处插入文本的小例子
2013/03/22 Javascript
使用javascript:将其它类型值转换成布尔类型值的解决方法详解
2013/05/07 Javascript
单击复制文字兼容各浏览器的完美解决方案
2013/07/04 Javascript
如何使用jquery easyui创建标签组件
2015/11/18 Javascript
javascript关于继承解析
2016/05/10 Javascript
AngularJs 动态加载模块和依赖
2016/09/15 Javascript
在vue中使用css modules替代scroped的方法
2018/03/10 Javascript
微信小程序之多列表的显示和隐藏功能【附源码】
2018/08/06 Javascript
详解vue开发中调用微信jssdk的问题
2019/04/16 Javascript
javascript 对象 与 prototype 原型用法实例分析
2019/11/11 Javascript
处理JavaScript值为undefined的7个小技巧
2020/07/28 Javascript
[03:10]超级美酒第四天 fy拉比克秀 大合集
2018/06/05 DOTA
python字典的常用操作方法小结
2016/05/16 Python
Python 通过URL打开图片实例详解
2017/06/01 Python
python 通过xml获取测试节点和属性的实例
2018/03/31 Python
python 删除非空文件夹的实例
2018/04/26 Python
详解python 利用echarts画地图(热力图)(世界地图,省市地图,区县地图)
2019/08/06 Python
QML使用Python的函数过程解析
2019/09/26 Python
Django中的模型类设计及展示示例详解
2020/05/29 Python
win10安装python3.6的常见问题
2020/07/01 Python
canvas像素画板的实现代码
2018/11/21 HTML / CSS
香港永安旅游网:Wing On Travel
2017/04/10 全球购物
日本索尼音乐商店:Sony Music Shop
2018/07/17 全球购物
武汉世纪畅想数字传播有限公司 .NET笔试题
2015/06/13 面试题
创业计划书的主要内容有哪些
2014/01/29 职场文书
C++程序员求职信
2014/05/07 职场文书
感恩教育月活动总结
2014/07/07 职场文书
化学教育专业求职信
2014/07/08 职场文书
创建绿色学校先进个人材料
2014/08/20 职场文书
永远是春天观后感
2015/06/12 职场文书
2016年企业安全生产月活动总结
2016/04/06 职场文书
Python使用Opencv打开笔记本电脑摄像头报错解问题及解决
2022/06/21 Python