国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > PHP > 正文

Yii框架實現圖片上傳的方法詳解

2024-05-04 23:57:22
字體:
來源:轉載
供稿:網友

本文實例講述了Yii框架實現圖片上傳的方法。分享給大家供大家參考,具體如下:

今天在網上看了下有關圖片上傳的教程,歷經挫折才調試好,現在把相關代碼及其說明貼出來,以供初次使用的朋友們參考。

Model:

<?phpclass 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:

<?phpclass 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目錄下

<?phpclass 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教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 香格里拉县| 彭泽县| 峡江县| 南阳市| 平潭县| 霸州市| 南京市| 聂拉木县| 长顺县| 江达县| 旺苍县| 新兴县| 屏南县| 桦川县| 久治县| 焦作市| 定边县| 长春市| 天峻县| 广宗县| 湘乡市| 自治县| 靖江市| 金寨县| 宿迁市| 塔河县| 奇台县| 富平县| 桃源县| 张家口市| 汉阴县| 漳州市| 昔阳县| 巴塘县| 津南区| 鸡泽县| 嵊泗县| 温州市| 宜兰县| 油尖旺区| 合作市|