------------------------------------------------html
下載地址在尾部web
1.前言:以前一直用KingEditor富文本編輯器,在國產編輯器中算是頂尖的插件。可是這個編輯器集成度較差,也好久沒有更新了,今天學習百度產品UEeditor使用!json
2.開發環境:VS2013+MVC5服務器
3.知識點:上傳加水印功能網絡
下載編輯器編輯器
各自選擇本身語言的版本。我這裏是.net版本就選擇.net版本 UTF-8ide
同時能夠選擇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的疑問歡迎留言!更多高級功能請訪問官方網站