标签:
目录:
------------------------------------------------
下载地址在尾部
1.前言:之前一直用KingEditor富文本编辑器,在国产编辑器中算是顶尖的插件。但是这个编辑器集成度较差,也很久没有更新了,今天学习百度产品UEeditor使用!
2.开发环境:VS2013+MVC5
3.知识点:上传加水印功能
各自选择自己语言的版本。我这里是.net版本就选择.net版本 UTF-8
同时可以选择Mini版本,Mini版本在日常也是够用的。开发版功能比较齐全,包括在线编辑WORD,地图,图表等功能。如果是普通的,比如博客类的,回复类使用的,使用mini版比较何时。
4.初次开始:
新建MVC5项目名为UEeditorForMVC,并解压下载的ueditor到Script文件夹下,utf8-net改名为UEeditor
初始部署使用:修改index.cshtml
@{ ViewBag.Title = "Home Page"; } <script src="~/Scripts/ueditor/ueditor.config.js"></script> <script src="~/Scripts/ueditor/ueditor.all.min.js"></script> <script> //加载编辑器 var ue = UE.getEditor(‘container‘, { }); </script> <script id="container" name="content" style=" height: 228px; " type="text/plain"> </script>
运行后出现效果,证明配置已经成功!
5.配置工具栏
有时候我们需要自定义工具栏,2个地方可以进行配置,一个是全局的配置文件ueitor.config.js,修改这个文件将导致整站所有编辑器一并修改
单独配置在加载编辑器时候触发:
<script> //加载编辑器 var ue = UE.getEditor(‘container‘, { toolbars: [[ ‘fullscreen‘, ‘source‘, ‘bold‘, ‘italic‘, ‘underline‘, ‘forecolor‘, ‘insertorderedlist‘, ‘fontfamily‘, ‘fontsize‘, ‘justifyleft‘, ‘justifycenter‘, ‘link‘, ‘unlink‘, ‘simpleupload‘, ‘snapscreen‘ ]] }); </script>
这个加载可以发现与config.js是对应的。包括接口路径,主题等,都可以单独配置
效果如下,我只配置了最常用的工具栏
6.设置和读取编辑器内容
ue.ready(function() { //设置编辑器的内容 ue.setContent(‘hello‘); //获取html内容,返回: <p>hello</p> var html = ue.getContent(); //获取纯文本内容,返回: hello var txt = ue.getContentTxt(); });
可以设置编辑器的内容。比如文章可以获取后调用
ue.setContent(‘hello‘);为编辑器设置内容
7.文件上传
文件上传是本文的主要内容,我们必须了解一下接口。
controller.ashx 这是一个处理文件,继承IHttpHandler接口。所有文件的上传必须经过这个文件处理
App_Code文件夹下的UploadHandler.cs为上传处理文件。
执行顺序由controller.ashx判断处理后调用UploadHandler。
初始上传会成功,但是没有图片显示
这是因为路径文件造成
研究发现net根目录下有文件config.json。这个是一个json格式的配置文件
这里可以配置所有上传时候的参数包括,上传路径,文件命名,远程抓取路径等
我们这里只修改第11行代码即可
"imageUrlPrefix": "/Scripts/ueditor/net/", /* 图片访问路径前缀 */
修改上传路径:在62行
8.加入水印
既然我们知道修改文件为上传文件,那么修改上传处理逻辑可以加入水印
添加一个水印类
using System; using System.Web; using System.Drawing; using System.Drawing.Imaging; using System.Drawing.Drawing2D; using System.IO; public class WaterMark { /// <summary> /// 图片水印 /// </summary> /// <param name="imgPath">服务器图片相对路径</param> /// <param name="filename">保存文件名</param> /// <param name="watermarkFilename">水印文件相对路径</param> /// <param name="watermarkStatus">图片水印位置 0=不使用 1=左上 2=中上 3=右上 4=左中 9=右下</param> /// <param name="quality">附加水印图片质量,0-100</param> /// <param name="watermarkTransparency">水印的透明度 1--10 10为不透明</param> public static void AddImageSignPic(string imgPath, string filename, string watermarkFilename, int watermarkStatus, int quality, int watermarkTransparency) { if(!File.Exists(imgPath)) return; byte[] _ImageBytes = File.ReadAllBytes(imgPath); Image img = Image.FromStream(new System.IO.MemoryStream(_ImageBytes)); watermarkFilename = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, watermarkFilename); if (!File.Exists(watermarkFilename)) return; Graphics g = Graphics.FromImage(img); //设置高质量插值法 //g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //设置高质量,低速度呈现平滑程度 //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; Image watermark = new Bitmap(watermarkFilename); if (watermark.Height >= img.Height || watermark.Width >= img.Width) return; ImageAttributes imageAttributes = new ImageAttributes(); ColorMap colorMap = new ColorMap(); colorMap.OldColor = Color.FromArgb(255, 0, 255, 0); colorMap.NewColor = Color.FromArgb(0, 0, 0, 0); ColorMap[] remapTable = { colorMap }; imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap); float transparency = 0.5F; if (watermarkTransparency >= 1 && watermarkTransparency <= 10) transparency = (watermarkTransparency / 10.0F); float[][] colorMatrixElements = { new float[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f}, new float[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f}, new float[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f}, new float[] {0.0f, 0.0f, 0.0f, transparency, 0.0f}, new float[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f} }; ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements); imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); int xpos = 0; int ypos = 0; switch (watermarkStatus) { case 1: xpos = (int)(img.Width * (float).01); ypos = (int)(img.Height * (float).01); break; case 2: xpos = (int)((img.Width * (float).50) - (watermark.Width / 2)); ypos = (int)(img.Height * (float).01); break; case 3: xpos = (int)((img.Width * (float).99) - (watermark.Width)); ypos = (int)(img.Height * (float).01); break; case 4: xpos = (int)(img.Width * (float).01); ypos = (int)((img.Height * (float).50) - (watermark.Height / 2)); break; case 5: xpos = (int)((img.Width * (float).50) - (watermark.Width / 2)); ypos = (int)((img.Height * (float).50) - (watermark.Height / 2)); break; case 6: xpos = (int)((img.Width * (float).99) - (watermark.Width)); ypos = (int)((img.Height * (float).50) - (watermark.Height / 2)); break; case 7: xpos = (int)(img.Width * (float).01); ypos = (int)((img.Height * (float).99) - watermark.Height); break; case 8: xpos = (int)((img.Width * (float).50) - (watermark.Width / 2)); ypos = (int)((img.Height * (float).99) - watermark.Height); break; case 9: xpos = (int)((img.Width * (float).99) - (watermark.Width)); ypos = (int)((img.Height * (float).99) - watermark.Height); break; } g.DrawImage(watermark, new Rectangle(xpos, ypos, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel, imageAttributes); ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo ici = null; foreach (ImageCodecInfo codec in codecs) { if (codec.MimeType.IndexOf("jpeg") > -1) ici = codec; } EncoderParameters encoderParams = new EncoderParameters(); long[] qualityParam = new long[1]; if (quality < 0 || quality > 100) quality = 80; qualityParam[0] = quality; EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam); encoderParams.Param[0] = encoderParam; if (ici != null) img.Save(filename, ici, encoderParams); else img.Save(filename); g.Dispose(); img.Dispose(); watermark.Dispose(); imageAttributes.Dispose(); } /// <summary> /// 文字水印 /// </summary> /// <param name="imgPath">服务器图片相对路径</param> /// <param name="filename">保存文件名</param> /// <param name="watermarkText">水印文字</param> /// <param name="watermarkStatus">图片水印位置 0=不使用 1=左上 2=中上 3=右上 4=左中 9=右下</param> /// <param name="quality">附加水印图片质量,0-100</param> /// <param name="fontname">字体</param> /// <param name="fontsize">字体大小</param> public static void AddImageSignText(string imgPath, string filename, string watermarkText, int watermarkStatus, int quality, string fontname, int fontsize) { byte[] _ImageBytes = File.ReadAllBytes(imgPath); Image img = Image.FromStream(new System.IO.MemoryStream(_ImageBytes)); Graphics g = Graphics.FromImage(img); Font drawFont = new Font(fontname, fontsize, FontStyle.Regular, GraphicsUnit.Pixel); SizeF crSize; crSize = g.MeasureString(watermarkText, drawFont); float xpos = 0; float ypos = 0; switch (watermarkStatus) { case 1: xpos = (float)img.Width * (float).01; ypos = (float)img.Height * (float).01; break; case 2: xpos = ((float)img.Width * (float).50) - (crSize.Width / 2); ypos = (float)img.Height * (float).01; break; case 3: xpos = ((float)img.Width * (float).99) - crSize.Width; ypos = (float)img.Height * (float).01; break; case 4: xpos = (float)img.Width * (float).01; ypos = ((float)img.Height * (float).50) - (crSize.Height / 2); break; case 5: xpos = ((float)img.Width * (float).50) - (crSize.Width / 2); ypos = ((float)img.Height * (float).50) - (crSize.Height / 2); break; case 6: xpos = ((float)img.Width * (float).99) - crSize.Width; ypos = ((float)img.Height * (float).50) - (crSize.Height / 2); break; case 7: xpos = (float)img.Width * (float).01; ypos = ((float)img.Height * (float).99) - crSize.Height; break; case 8: xpos = ((float)img.Width * (float).50) - (crSize.Width / 2); ypos = ((float)img.Height * (float).99) - crSize.Height; break; case 9: xpos = ((float)img.Width * (float).99) - crSize.Width; ypos = ((float)img.Height * (float).99) - crSize.Height; break; } g.DrawString(watermarkText, drawFont, new SolidBrush(Color.White), xpos + 1, ypos + 1); g.DrawString(watermarkText, drawFont, new SolidBrush(Color.Black), xpos, ypos); ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo ici = null; foreach (ImageCodecInfo codec in codecs) { if (codec.MimeType.IndexOf("jpeg") > -1) ici = codec; } EncoderParameters encoderParams = new EncoderParameters(); long[] qualityParam = new long[1]; if (quality < 0 || quality > 100) quality = 80; qualityParam[0] = quality; EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam); encoderParams.Param[0] = encoderParam; if (ici != null) img.Save(filename, ici, encoderParams); else img.Save(filename); g.Dispose(); img.Dispose(); } /// <summary> /// 返回文件扩展名,不含“.” /// </summary> /// <param name="_filepath">文件全名称</param> /// <returns>string</returns> public static string GetFileExt(string _filepath) { if (string.IsNullOrEmpty(_filepath)) { return ""; } if (_filepath.LastIndexOf(".") > 0) { return _filepath.Substring(_filepath.LastIndexOf(".") + 1); //文件扩展名,不含“.” } return ""; } public static string GetRamCode() { return DateTime.Now.ToString("yyyyMMddHHmmssffff"); } }
/// <summary>
/// 文字水印
/// </summary>
/// <param name="imgPath">服务器图片相对路径</param>
/// <param name="filename">保存文件名</param>
/// <param name="watermarkText">水印文字</param>
/// <param name="watermarkStatus">图片水印位置 0=不使用 1=左上 2=中上 3=右上 4=左中 9=右下</param>
/// <param name="quality">附加水印图片质量,0-100</param>
/// <param name="fontname">字体</param>
/// <param name="fontsize">字体大小</param>
AddImageSignPic方法参数解析
这样我们修改自带的UploadHandler.cs第68行try方法为
try
{
if (!Directory.Exists(Path.GetDirectoryName(localPath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(localPath));
}
file.SaveAs(localPath);
WaterMark.AddImageSignText(localPath, localPath,
"ymnets", 9,
80, "Tahoma", 12);
//WaterMark.AddImageSignPic(serverFileName, serverFileName,
// "传入水印图片路径", 9,
// 80, 5);
Result.Url = savePath;
Result.State = UploadState.Success;
}
保存后调用写水印函数,完整的
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Web; /// <summary> /// UploadHandler 的摘要说明 /// </summary> public class UploadHandler : Handler { public UploadConfig UploadConfig { get; private set; } public UploadResult Result { get; private set; } public UploadHandler(HttpContext context, UploadConfig config) : base(context) { this.UploadConfig = config; this.Result = new UploadResult() { State = UploadState.Unknown }; } public override void Process() { byte[] uploadFileBytes = null; string uploadFileName = null; if (UploadConfig.Base64) { uploadFileName = UploadConfig.Base64Filename; uploadFileBytes = Convert.FromBase64String(Request[UploadConfig.UploadFieldName]); } else { var file = Request.Files[UploadConfig.UploadFieldName]; uploadFileName = file.FileName; if (!CheckFileType(uploadFileName)) { Result.State = UploadState.TypeNotAllow; WriteResult(); return; } if (!CheckFileSize(file.ContentLength)) { Result.State = UploadState.SizeLimitExceed; WriteResult(); return; } uploadFileBytes = new byte[file.ContentLength]; try { file.InputStream.Read(uploadFileBytes, 0, file.ContentLength); } catch (Exception) { Result.State = UploadState.NetworkError; WriteResult(); } Result.OriginFileName = uploadFileName; var savePath = PathFormatter.Format(uploadFileName, UploadConfig.PathFormat); var localPath = Server.MapPath(savePath); try { if (!Directory.Exists(Path.GetDirectoryName(localPath))) { Directory.CreateDirectory(Path.GetDirectoryName(localPath)); } file.SaveAs(localPath); WaterMark.AddImageSignText(localPath, localPath, "ymnets", 9, 80, "Tahoma", 12); //WaterMark.AddImageSignPic(serverFileName, serverFileName, // "传入水印图片路径", 9, // 80, 5); Result.Url = savePath; Result.State = UploadState.Success; } catch (Exception e) { Result.State = UploadState.FileAccessError; Result.ErrorMessage = e.Message; } finally { WriteResult(); } } } private void WriteResult() { this.WriteJson(new { state = GetStateMessage(Result.State), url = Result.Url, title = Result.OriginFileName, original = Result.OriginFileName, error = Result.ErrorMessage }); } private string GetStateMessage(UploadState state) { switch (state) { case UploadState.Success: return "SUCCESS"; case UploadState.FileAccessError: return "文件访问出错,请检查写入权限"; case UploadState.SizeLimitExceed: return "文件大小超出服务器限制"; case UploadState.TypeNotAllow: return "不允许的文件格式"; case UploadState.NetworkError: return "网络错误"; } return "未知错误"; } private bool CheckFileType(string filename) { var fileExtension = Path.GetExtension(filename).ToLower(); return UploadConfig.AllowExtensions.Select(x => x.ToLower()).Contains(fileExtension); } private bool CheckFileSize(int size) { return size < UploadConfig.SizeLimit; } } public class UploadConfig { /// <summary> /// 文件命名规则 /// </summary> public string PathFormat { get; set; } /// <summary> /// 上传表单域名称 /// </summary> public string UploadFieldName { get; set; } /// <summary> /// 上传大小限制 /// </summary> public int SizeLimit { get; set; } /// <summary> /// 上传允许的文件格式 /// </summary> public string[] AllowExtensions { get; set; } /// <summary> /// 文件是否以 Base64 的形式上传 /// </summary> public bool Base64 { get; set; } /// <summary> /// Base64 字符串所表示的文件名 /// </summary> public string Base64Filename { get; set; } } public class UploadResult { public UploadState State { get; set; } public string Url { get; set; } public string OriginFileName { get; set; } public string ErrorMessage { get; set; } } public enum UploadState { Success = 0, SizeLimitExceed = -1, TypeNotAllow = -2, FileAccessError = -3, NetworkError = -4, Unknown = 1, }
这次我们再次上传预览效果
成功生成一个文字水印。这个水印类也包含了图片LOGO形式的
WaterMark.AddImageSignPic(serverFileName, serverFileName,
"传入水印图片路径", 9,
80, 5);
注掉文字的替换这句:
我下载了博客园的LOGO,那么结果显然
模糊度和图片透明度都有关系.
文章内容到此结束,如果有关于ueditor的疑问欢迎留言!更多高级功能请访问官方网站
构建ASP.NET MVC5+EF6+EasyUI 1.4.3+Unity4.x注入的后台管理系统(57)-插件---ueditor使用
标签:
原文地址:http://www.cnblogs.com/ymnets/p/5247638.html