thinkphp5整合最新ueditor,支持图片加水印

UEditor是由百度web前端研发部开发所见即所得富文本web编辑器,具有轻量,可定制,注重用户体验等特点,开源基于MIT协议,允许自由使用和修改代码...


thinkphp5 TPshop项目开发中用到了富文本编辑器,选择有很多,不过资料手册文档最齐全的当然属百度的ueditor,可是发现TPshop2.05版之前使用的是ueditor1.26老版本,在上传图片时需要依赖flash,而很多新版本浏览器开始禁用flash,那么问题来了,ueditor需要升级才能兼容。

编辑器效果
thinkphp5整合最新ueditor,支持图片加水印_第1张图片
简单贴一段主要核心代码,有不妥的地方可以多多交流
  1.  href="__ROOT__/public/plugins/Ueditor/ueditor.config.js"/>
  2.  href="__ROOT__/public/plugins/Ueditor/ueditor.all.min.js"/>
  3.  type="text/javascript" charset="utf-8" src="__ROOT__/public/plugins/Ueditor/lang/zh-cn/zh-cn.js">
  4.  src="__ROOT__/public/static/js/layer/laydate/laydate.js">
  5.   class="span12 ckeditor" id="post_content" name="content" title="">{$info.content}  
  6.  type="text/javascript">
  7.     var url="{:url('Ueditor/index',array('savePath'=>'article'))}";
  8.     var ue = UE.getEditor('post_content',{
  9.         serverUrl :url,
  10.         zIndex: 999,
  11.         initialFrameWidth: "80%", //初化宽度
  12.         initialFrameHeight: 300, //初化高度            
  13.         focus: false, //初始化时,是否让编辑器获得焦点true或false
  14.         maximumWords: 99999, removeFormatAttributes: 'class,style,lang,width,height,align,hspace,valign',//允许的最大字符数 'fullscreen',
  15.         pasteplain:false, //是否默认为纯文本粘贴。false为不使用纯文本粘贴,true为使用纯文本粘贴
  16.         autoHeightEnabled: true
  17.     });
  18.     
复制代码
php接收代码
  1. class Ueditor extends Base
  2. {
  3.     private $sub_name = array('date', 'Y/m-d');
  4.     private $savePath = 'temp/';
  5.     public function __construct()
  6.     {
  7.         parent::__construct();
  8.         
  9.         //header('Access-Control-Allow-Origin: http://www.baidu.com'); //设置http://www.baidu.com允许跨域访问
  10.         //header('Access-Control-Allow-Headers: X-Requested-With,X_Requested_With'); //设置允许的跨域header
  11.         
  12.         date_default_timezone_set("Asia/Shanghai");
  13.         
  14.         $this->savePath = I('savepath','temp').'/';
  15.         
  16.         error_reporting(E_ERROR | E_WARNING);
  17.         
  18.         header("Content-Type: text/html; charset=utf-8");
  19.     }
  20.     
  21.     public function index(){
  22.         
  23.         $CONFIG2 = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents("./public/plugins/Ueditor/php/config.json")), true);
  24.         $action = $_GET['action'];
  25.         
  26.         switch ($action) {
  27.             case 'config':
  28.                 $result =  json_encode($CONFIG2);
  29.                 break;
  30.             /* 上传图片 */
  31.             case 'uploadimage':
  32.                 $fieldName = $CONFIG2['imageFieldName'];
  33.                 $result = $this->upFile($fieldName);
  34.                 break;
  35.             /* 上传涂鸦 */
  36.             case 'uploadscrawl':
  37.                 $config = array(
  38.                     "pathFormat" => $CONFIG2['scrawlPathFormat'],
  39.                     "maxSize" => $CONFIG2['scrawlMaxSize'],
  40.                     "allowFiles" => $CONFIG2['scrawlAllowFiles'],
  41.                     "oriName" => "scrawl.png"
  42.                 );
  43.                 $fieldName = $CONFIG2['scrawlFieldName'];
  44.                 $base64 = "base64";
  45.                 $result = $this->upBase64($config,$fieldName);
  46.                 break;
  47.             /* 上传视频 */
  48.             case 'uploadvideo':
  49.                 $fieldName = $CONFIG2['videoFieldName'];
  50.                 $result = $this->upFile($fieldName);
  51.                 break;
  52.             /* 上传文件 */
  53.             case 'uploadfile':
  54.                 $fieldName = $CONFIG2['fileFieldName'];
  55.                 $result = $this->upFile($fieldName);
  56.                 break;
  57.             /* 列出图片 */
  58.             case 'listimage':
  59.                 $allowFiles = $CONFIG2['imageManagerAllowFiles'];
  60.                 $listSize = $CONFIG2['imageManagerListSize'];
  61.                 $path = $CONFIG2['imageManagerListPath'];
  62.                 $get =$_GET;
  63.                 $result =$this->fileList($allowFiles,$listSize,$get);
  64.                 break;
  65.             /* 列出文件 */
  66.             case 'listfile':
  67.                 $allowFiles = $CONFIG2['fileManagerAllowFiles'];
  68.                 $listSize = $CONFIG2['fileManagerListSize'];
  69.                 $path = $CONFIG2['fileManagerListPath'];
  70.                 $get = $_GET;
  71.                 $result = $this->fileList($allowFiles,$listSize,$get);
  72.                 break;
  73.             /* 抓取远程文件 */
  74.             case 'catchimage':
  75.                 $config = array(
  76.                     "pathFormat" => $CONFIG2['catcherPathFormat'],
  77.                     "maxSize" => $CONFIG2['catcherMaxSize'],
  78.                     "allowFiles" => $CONFIG2['catcherAllowFiles'],
  79.                     "oriName" => "remote.png"
  80.                 );
  81.                 $fieldName = $CONFIG2['catcherFieldName'];
  82.                 /* 抓取远程图片 */
  83.                 $list = array();
  84.                 isset($_POST[$fieldName]) ? $source = $_POST[$fieldName] : $source = $_GET[$fieldName];
  85.                 
  86.                 foreach($source as $imgUrl){
  87.                     $info = json_decode($this->saveRemote($config,$imgUrl),true);
  88.                     array_push($list, array(
  89.                         "state" => $info["state"],
  90.                         "url" => $info["url"],
  91.                         "size" => $info["size"],
  92.                         "title" => htmlspecialchars($info["title"]),
  93.                         "original" => htmlspecialchars($info["original"]),
  94.                         "source" => htmlspecialchars($imgUrl)
  95.                     ));
  96.                 }
  97.                 $result = json_encode(array(
  98.                     'state' => count($list) ? 'SUCCESS':'ERROR',
  99.                     'list' => $list
  100.                 ));
  101.                 break;
  102.             default:
  103.                 $result = json_encode(array(
  104.                     'state' => '请求地址出错'
  105.                 ));
  106.                 break;
  107.         }
  108.         /* 输出结果 */
  109.         if(isset($_GET["callback"])){
  110.             if(preg_match("/^[\w_]+$/", $_GET["callback"])){
  111.                 echo htmlspecialchars($_GET["callback"]).'('.$result.')';
  112.             }else{
  113.                 echo json_encode(array(
  114.                     'state' => 'callback参数不合法'
  115.                 ));
  116.             }
  117.         }else{
  118.             echo $result;
  119.         }
  120.     }
  121.     
  122.     //上传文件
  123.     private function upFile($fieldName){
  124.         $file = request()->file($fieldName);
  125.         
  126.         $result = $this->validate(
  127.                 ['file2' => $file],
  128.                 ['file2'=>'image','file2'=>'fileSize:40000000'],
  129.                 ['file2.image' => '上传文件必须为图片','file2.fileSize' => '上传文件过大']
  130.         );
  131.         
  132.         if (true !== $result || empty($file)) {
  133.             $state = "ERROR" . $result;
  134.         }else{
  135.             // 移动到框架应用根目录/public/uploads/ 目录下
  136.             $this->savePath = $this->savePath.date('Y').'/'.date('m-d').'/';
  137.             // 使用自定义的文件保存规则
  138.             $info = $file->rule(function ($file) {
  139.                 return  md5(mt_rand());
  140.             })->move('public/upload/'.$this->savePath);
  141.         }
  142.         
  143.         if($info){
  144.             $data = array(
  145.                 'state' => 'SUCCESS',
  146.                 'url' => '/public/upload/'.$this->savePath.$info->getSaveName(),
  147.                 'title' => $info->getFilename(),
  148.                 'original' => $info->getFilename(),
  149.                 'type' => '.' . $info->getExtension(),
  150.                 'size' => $info->getSize(),
  151.             );
  152.             //图片加水印
  153.             if($this->savePath=='Goods/'){
  154.                 $image = new \Think\Image();
  155.                 $water = tpCache('water');
  156.                 $imgresource = ".".$data['url'];
  157.                 $image->open($imgresource);
  158.                 if($water['is_mark']==1 && $image->width()>$water['mark_width'] && $image->height()>$water['mark_height']){
  159.                     if($water['mark_type'] == 'text'){
  160.                         $image->text($water['mark_txt'],'./hgzb.ttf',20,'#000000',9)->save($imgresource);
  161.                     }else{
  162.                         $image->water(".".$water['mark_img'],9,$water['mark_degree'])->save($imgresource);
  163.                     }
  164.                 }
  165.             }
  166.         }else{
  167.             $data = array('state' => $state.$info->getError());
  168.         }
  169.         return json_encode($data);
  170.     }
  171.     //列出图片
  172.     private function fileList($allowFiles,$listSize,$get){
  173.         $dirname = './public/upload/';
  174.         $allowFiles = substr(str_replace(".","|",join("",$allowFiles)),1);
  175.         /* 获取参数 */
  176.         $size = isset($get['size']) ? htmlspecialchars($get['size']) : $listSize;
  177.         $start = isset($get['start']) ? htmlspecialchars($get['start']) : 0;
  178.         $end = $start + $size;
  179.         /* 获取文件列表 */
  180.         $path = $dirname;
  181.         $files = $this->getFiles($path,$allowFiles);
  182.         if(!count($files)){
  183.             return json_encode(array(
  184.                 "state" => "no match file",
  185.                 "list" => array(),
  186.                 "start" => $start,
  187.                 "total" => count($files)
  188.             ));
  189.         }
  190.         /* 获取指定范围的列表 */
  191.         $len = count($files);
  192.         for($i = min($end, $len) - 1, $list = array(); $i < $len && $i >= 0 && $i >= $start; $i--){
  193.             $list[] = $files[$i];
  194.         }
  195.         /* 返回数据 */
  196.         $result = json_encode(array(
  197.             "state" => "SUCCESS",
  198.             "list" => $list,
  199.             "start" => $start,
  200.             "total" => count($files)
  201.         ));
  202.         return $result;
  203.     }
  204.        /*
  205.      * 遍历获取目录下的指定类型的文件
  206.      * @param $path
  207.      * @param array $files
  208.      * @return array
  209.     */
  210.     private function getFiles($path,$allowFiles,&$files = array()){
  211.         if(!is_dir($path)) return null;
  212.         if(substr($path,strlen($path)-1) != '/') $path .= '/';
  213.         $handle = opendir($path);
  214.             
  215.         while(false !== ($file = readdir($handle))){
  216.             if($file != '.' && $file != '..'){
  217.                 $path2 = $path.$file;
  218.                 if(is_dir($path2)){
  219.                     $this->getFiles($path2,$allowFiles,$files);
  220.                 }else{
  221.                     if(preg_match("/\.(".$allowFiles.")$/i",$file)){
  222.                         $files[] = array(
  223.                             'url' => substr($path2,1),
  224.                             'mtime' => filemtime($path2)
  225.                         );
  226.                     }
  227.                 }
  228.             }
  229.         }        
  230.         return $files;
  231.     }

复制代码
更多详细代码可以下载TPshop源码查看

你可能感兴趣的:(php技术,tpshop,tpshop开发,javascript,html5,开源商城,thinkphp,tpshop,ueditor,html5,tpshop商城)