CKEditor二次开发----为CKEditor增加添加水印的功能

 

在CKEditor上增加添加水印的功能,相信大家都没有见过。

 

CKEditor的前身就是FCKEditor,FCKEditor自3.0后就改称为CKEditor。

话不多说,,我们开始吧,,

 

首先,修改对CKEditor引入的那部分javascript,代码如下:

 

 

<script type="text/javascript">
	CKEDITOR.replace('content',addWaterMarkButton(this));
        function addWaterMarkButton(editor){
           CKEDITOR.on('dialogDefinition', function( ev ){
               var dialogName = ev.data.name;
               var dialogDefinition = ev.data.definition;
               if ( dialogName == 'image' ){
                   var infoTab = dialogDefinition.getContents( 'info' );
                   infoTab.add({
                       type : 'button',
                       id : 'upload_image',
                       align : 'center',
                       label : '添加水印',
                       onClick : function( evt ){
                           var thisDialog = this.getDialog();
                           var txtUrlObj = thisDialog.getContentElement('info', 'txtUrl');
                           var txtUrlId = txtUrlObj.getInputElement().$.id;
                           addWaterMark(txtUrlId);
                       }
                   }, 'browse'); //place front of the browser button
               }
           });
       }
        function addWaterMark(theURLElementId){
           var watermark = "myCkeditor/watermark.jsp"; //这是我自己的处理文件/图片上传的页面URL
           var imgUrl = window.showModalDialog(watermark,null,"dialogWidth:360px;dialogHeight:120px;help:no;status:no");
           var urlObj = document.getElementById(theURLElementId);
           urlObj.value = imgUrl;
           urlObj.fireEvent("onchange"); //触发url文本框的onchange事件,以便预览图片
       }
	</script>

 

以上的部分,我想对于了解CKEditor的朋友一定非常熟悉了,,我也就不多说了,

 

 完成这个以后,我们可以做一个上传页面,如上代码"myCkeditor/watermark.jsp"; //这是我自己的处理文件/图片上传的页面URL

 

 

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%@taglib uri="/struts-tags" prefix="s"%>
<%
String image= (String)request.getParameter("image");
 %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<title>添加水印</title>
	</head>
	<body>
		<iframe name="smz" width="0" height="0" frameborder="0"
			style="display: none"></iframe>
		<font color="red"><s:property value="#request.errorMessage" />
		</font>
		<form action="watermark" method="post" enctype="multipart/form-data"
			name="watermark" target="smz">
			<%
			if(image!=null) 
			{
			out.print("原文件:<img src='.."+image+"'/>");
			out.print("<input type='hidden' name='sourceimage' value='"+image+"'/><br>");
			}
			else {
			out.print("原文件:<input type='file' name='sourcefile' class='button'><br>");
			}
			%>
			水印:
			<input type="file" name="markfile" class="button"><br>
			文字:
			<input type="text" name="text" size="24"class="button"><br>
			文字色彩:
			<select name="textcolor">
			<option value='red'>红色</option>
			<option value='pink'>粉红</option>
			<option value='gray'>灰色</option>
			<option value='blue'>蓝色</option>
			<option value='green'>绿色</option>
			<option value='black'>黑色</option>
			</select>
			<br>
			<input type="submit" name="submit" value="执行" class="button">
		</form>
		<input type="hidden" name="pagePath" id="_page_path"
			value="<%String p=(String)session.getAttribute("pagePath");if(p!=null)out.print(p);session.removeAttribute("pagePath"); %>" />
		<script type="text/javascript">
	    var _page_path = document.getElementById("_page_path").value;
	    if(null!=_page_path  && ""!=_page_path){
	    
	    //alert(_page_path);
	    	window.returnValue=_page_path;
	       	window.close();
	    }
		</script>
	</body>
</html>

 

再接下来,我们就要做Action,即如上所示的<form action="watermark" method="post" enctype="multipart/form-data"

			name="watermark" target="smz">

 

package com.burning.EasyCMS.myCkeditor;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.swing.ImageIcon;

import org.apache.struts2.ServletActionContext;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class WaterMark {
	private static int wid = 0;
	private static int het = 0;
	private static final long serialVersionUID = 572146812454l;
	private static final int BUFFER_SIZE = 16 * 1024;

	private File sourcefile;
	private String sourceimage;
	private File markfile;
	private String text;
	private String textcolor;

	public static boolean createMark(String filePath, String watermark,
			String text, String savePath, Color color) {
		ImageIcon imgIcon = new ImageIcon(filePath);
		Image theImg = imgIcon.getImage();
		ImageIcon waterIcon = new ImageIcon(watermark);
		Image waterImg = waterIcon.getImage();

		if (watermark != null && !watermark.equals("")) {
			ImageIcon markIcon = new ImageIcon(watermark);
			Image markImg = markIcon.getImage();
			wid = markImg.getWidth(null); 
			het = markImg.getHeight(null);
		}


		int width = theImg.getWidth(null); 
		int height = theImg.getHeight(null); 

		BufferedImage bimage = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);

		Graphics2D g = bimage.createGraphics();
		g.setColor(color); 
		g.setBackground(Color.white);
		g.drawImage(theImg, 0, 0, null);
		g.drawImage(waterImg, width - wid, height - het, null); 
		g.drawString(text, width - 120, height - 12);

		try {
			FileOutputStream out = new FileOutputStream(savePath);
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
			JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bimage);
			param.setQuality(50f, true);
			encoder.encode(bimage, param);
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("水印失败");
			return false;
		} finally {
			System.gc();
		}
		System.out.println("水印成功");
		return true;
	}

	private static void copy(File src, File dst) {
		try {
			InputStream in = null;
			OutputStream out = null;
			try {
				in = new BufferedInputStream(new FileInputStream(src),
						BUFFER_SIZE);
				out = new BufferedOutputStream(new FileOutputStream(dst),
						BUFFER_SIZE);
				byte[] buffer = new byte[BUFFER_SIZE];
				while (in.read(buffer) > 0) {
					out.write(buffer);
				}
			} finally {
				if (null != in) {
					in.close();
				}
				if (null != out) {
					out.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public Color makeColor(String color) {
		Color c = null;
		if (color == null) {
			c = Color.black;
		} else if (color.equals("red")) {
			c = Color.red;
		} else if (color.equals("blue")) {
			c = Color.blue;
		} else if (color.equals("green")) {
			c = Color.green;
		} else if (color.equals("gray")) {
			c = Color.gray;
		} else if (color.equals("green")) {
			c = Color.green;
		} else if (color.equals("pink")) {
			c = Color.pink;
		} else {
			c = Color.black;
		}
		return c;
	}

	public String watermark() {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		try {
			String mark = null;
			String source = null;
			String serverPath = ServletActionContext.getServletContext()
					.getRealPath("\\");
			if (sourcefile != null) {
				String fileName = new Date().getTime() + "1.jpg";
				String path = serverPath + "upload\\image\\";
				File imageFile = new File(path + fileName);
				copy(sourcefile, imageFile);
				source = path + fileName;
			} else {
				source = serverPath + sourceimage;
			}
			if (markfile != null) {
				String fileName2 = new Date().getTime() + "2.jpg";
				String path = serverPath + "upload\\image\\";
				File imageFile2 = new File(path + fileName2);
				copy(markfile, imageFile2);
				mark = path + fileName2;
			} else {
				mark = serverPath + "myCkeditor\\transparent.gif";
			}
			Color c = makeColor(textcolor);
			if (text == null)
				text = "";
			String fileName = new Date().getTime() + ".jpg";
			String savepath = serverPath + "upload\\image\\" + fileName;
			System.out.println("source:"+source);
			System.out.println("mark:"+mark);
			System.out.println("text:"+text);
			System.out.println("savepath:"+savepath);
			if (createMark(source, mark, text, savepath, c))
			{
				session.setAttribute("pagePath", "upload\\image\\" + fileName);
				return "success";
			}
			else
				return "fail";
		} catch (Exception e) {
			request.setAttribute("errorMessage", "图片上传未成功");
			return "fail";
		}
	}

	public File getSourcefile() {
		return sourcefile;
	}

	public void setSourcefile(File sourcefile) {
		this.sourcefile = sourcefile;
	}

	public String getSourceimage() {
		return sourceimage;
	}

	public void setSourceimage(String sourceimage) {
		this.sourceimage = sourceimage;
	}

	public File getMarkfile() {
		return markfile;
	}

	public void setMarkfile(File markfile) {
		this.markfile = markfile;
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}

	public String getTextcolor() {
		return textcolor;
	}

	public void setTextcolor(String textcolor) {
		this.textcolor = textcolor;
	}
}

 好了,到此我们的二次开发就结束了,,谢谢,本文为原创,但也在网上学习了很多朋友的知识,再次谢谢大家 ,希望对大家有用。

以下为运行效果

添加水印的界面

(添加水印的界面)

(添加水印成功后界面)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
添加配置到CKEditor 5 Decoupled Document Build中,您需要执行以下步骤: 1. 打开您的`webpack.config.js`文件,这是您的CKEditor 5应用程序的配置文件。 2. 找到`module.exports`对象中的`module`属性,并在`rules`数组中添加以下代码: ```javascript { test: /\.css$/, use: ['style-loader', 'css-loader'], exclude: /ckeditor5-[^/\\]+[/\\]theme[/\\].+\.css$/ }, { test: /ckeditor5-[^/\\]+[/\\]theme[/\\]icons[/\\][^/\\]+\.svg$/, use: ['raw-loader'] }, { test: /ckeditor5-[^/\\]+[/\\]theme[/\\].+\.css$/, use: ['style-loader', 'css-loader'], }, { test: /ckeditor5-[^/\\]+[/\\]theme[/\\]loader\.js$/, use: [ { loader: 'style-loader', options: { injectType: 'singletonStyleTag', attributes: { 'data-cke': true } } }, { loader: 'postcss-loader', options: styles.getPostCssConfig({ themeImporter: { themePath: require.resolve('@ckeditor/ckeditor5-theme-lark') }, minify: true }) } ] } ``` 这将允许您在Decoupled Document Build中使用CSS样式。 3. 找到`module.exports`对象中的`plugins`属性,并在其中添加以下代码: ```javascript new CKEditorWebpackPlugin({ language: 'en', translationsOutputFile: /app[\\/]translations\.json$/, additionalLanguages: 'all' }) ``` 这将启用CKEditor 5的语言支持,并生成翻译文件。 4. 找到您的`src`文件夹,然后在其中创建一个名为`ckeditor.js`的文件。在该文件中,添加以下代码: ```javascript import ClassicEditor from '@ckeditor/ckeditor5-editor-classic/src/classiceditor'; import Essentials from '@ckeditor/ckeditor5-essentials/src/essentials'; import Bold from '@ckeditor/ckeditor5-basic-styles/src/bold'; import Italic from '@ckeditor/ckeditor5-basic-styles/src/italic'; import Paragraph from '@ckeditor/ckeditor5-paragraph/src/paragraph'; ClassicEditor.create(document.querySelector('#editor'), { plugins: [Essentials, Bold, Italic, Paragraph], toolbar: ['bold', 'italic'] }) .then(editor => { console.log(editor); }) .catch(error => { console.error(error); }); ``` 这将初始化ClassicEditor,并创建一个具有加粗和斜体工具栏按钮的编辑器。 5. 在您的应用程序中添加一个`<div>`元素,并为其指定一个`id`属性,例如: ```html <div id="editor"></div> ``` 这将使编辑器显示在您的应用程序中。 现在,您已经成功地将CKEditor 5 Decoupled Document Build集成到您的应用程序中,并且已经添加了一些自定义配置。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值