現有一個需求,在PHPCMS內容發布管理里面發布一篇內容,要求上傳一張圖片,傳上去大小是160*60px,然后同時自動生成一張75*75px的縮略圖,和一張48*48px的縮略圖.
解決方案:
①在模型添加字段里面添加三個圖片字段,分別是thumb,這個字段貌似默認就有,有就不用添加,thumb2,thumb3,第一個字段thumb設置圖片寬高160*160,其他字段填不填都無所謂.
②在content模塊的content控制器的add方法,modules/content/content.php,添加如下代碼:
- //手機游戲平臺站點上傳縮略圖,自動生成75X75,48X48的縮略圖
- $siteid=$this->siteid;//獲取當前站點siteid
- if ($siteid==3) {
- $rawpic=isset($_POST['info']['thumb'])?$_POST['info']['thumb']:'';
- //如果上傳了第一張縮略圖
- if ($rawpic) {
- $new75_75=thumb($rawpic,75,75);
- $new48_48=thumb($rawpic,48,48);
- }
- $_POST['info']['thumb2']=$new75_75;
- $_POST['info']['thumb3']=$new48_48;
- }
因為PHPCMS的全局函數global.func.php包含了縮略圖函數,因此上面的代碼我們可以直接使用這個thumb函數,代碼如下:
- function thumb($imgurl, $width = 100, $height = 100 ,$autocut = 1, $smallpic = 'nopic.gif') {
- global $image;
- $upload_url = pc_base::load_config('system','upload_url');
- $upload_path = pc_base::load_config('system','upload_path');
- if(emptyempty($imgurl)) return IMG_PATH.$smallpic;
- $imgurl_replace= str_replace($upload_url, '', $imgurl);
- if(!extension_loaded('gd') || strpos($imgurl_replace, '://')) return $imgurl;
- if(!file_exists($upload_path.$imgurl_replace)) return IMG_PATH.$smallpic;//開源軟件:Vevb.com
- list($width_t, $height_t, $type, $attr) = getimagesize($upload_path.$imgurl_replace);
- if($width>=$width_t || $height>=$height_t) return $imgurl;
- www.49028c.com
- $newimgurl = dirname($imgurl_replace).'/thumb_'.$width.'_'.$height.'_'.basename($imgurl_replace);
- if(file_exists($upload_path.$newimgurl)) return $upload_url.$newimgurl;
- if(!is_object($image)) {
- pc_base::load_sys_class('image','','0');
- $image = new image(1,0);
- }
- return $image->thumb($upload_path.$imgurl_replace, $upload_path.$newimgurl, $width, $height, '', $autocut) ? $upload_url.$newimgurl : $imgurl;
- }
這樣就把生成的75*75和48*48的兩張圖片的路徑存入了數據庫表中對應的字段,同理在edit方法里復制這段代碼.
③另外,為了在添加內容的時候方便,不顯示thumb2和thumb3的上傳縮略圖的標簽,因為它是函數自動生成的,而且也無需編輯手動上傳,因此把它給隱藏掉比較好,在content控制器對應的模板content_add.tpl.php和content_edit.tpl.php的底部,有一段jquery包含的代碼中添加如下代碼:
- /*
- * 手機平臺站點隱藏縮略圖2和縮略圖3
- */
- $("#thumb2,#thumb3").parent().hide();
- $("#thumb2,#thumb3").parent().prev().hide();
這樣發布文章的編輯器就隱藏其他兩個縮略圖字段了.
新聞熱點
疑難解答