zoukankan      html  css  js  c++  java
  • kindeditor编辑器图片水印

    //upload_pic.ashx源码

    <%@ webhandler Language="C#" class="edit_html_upload_pic" %>
    using System;
    using System.Collections;
    using System.Web;
    using System.IO;
    using System.Globalization;
    using LitJson;
    using System.Web.SessionState;
    using System.Drawing;  
    using System.Drawing.Imaging;  
    public class edit_html_upload_pic : IHttpHandler, IRequiresSessionState
    {
        private HttpContext context;
    
        public void ProcessRequest(HttpContext context)
        {
            String aspxUrl = context.Request.Path.Substring(0, context.Request.Path.LastIndexOf("/") + 1);
    
            //每个用户文件夹独立IRequiresSessionState 
            String sessionUploadPath = String.Empty;
            if (HttpContext.Current.Session["edit_upload_folder"] != null)
            {
                sessionUploadPath = HttpContext.Current.Session["edit_upload_folder"].ToString() + "/";
            }
    
            //文件保存目录路径
            String savePath = "../../" + getConfigAppSettings("uploadFolder") + "/" + sessionUploadPath;
            //文件保存目录URL
            String saveUrl = aspxUrl + "../../" + getConfigAppSettings("uploadFolder") + "/" + sessionUploadPath;
    
            //定义允许上传的文件扩展名
            Hashtable extTable = new Hashtable();
            extTable.Add("image", "gif,jpg,jpeg,png,bmp");
            extTable.Add("flash", "swf,flv");
            extTable.Add("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
            extTable.Add("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");
    
            //最大文件大小
            int maxSize = 2000000;//2m
            this.context = context;
    
            HttpPostedFile imgFile = context.Request.Files["imgFile"];
            if (imgFile == null)
            {
                showError("请选择文件。");
            }
    
            String dirPath = context.Server.MapPath(savePath);
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }
    
            String dirName = context.Request.QueryString["dir"] != null ? context.Request.QueryString["dir"] : "image";
            String fileName = imgFile.FileName;
            String fileExt = Path.GetExtension(fileName).ToLower();
    
            if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(((String)extTable[dirName]).Split(','), fileExt.Substring(1).ToLower()) == -1)
            {
                showError("上传文件扩展名是不允许的扩展名。
    只允许" + ((String)extTable[dirName]) + "格式。");
            }
            if (dirName == "image")
            {
                if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize)
                {
                    showError("上传文件大小超过限制。");
                }
                if (!isPic(imgFile))
                {
                    showError("上传文件不合法!");
                }
            }
    
    
    
    
    
            //创建文件夹
            //dirPath += dirName + "/";
            //saveUrl += dirName + "/";
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }
            String ymd = DateTime.Now.ToString("yyyyMM", DateTimeFormatInfo.InvariantInfo);
            dirPath += ymd + "/";
            saveUrl += ymd + "/";
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }
            
            //edit_upload_fileName
            //string sessionUploadFileName = string.Empty;
            //if (HttpContext.Current.Session["edit_upload_fileName"] != null)
            //{
            //    sessionUploadFileName = HttpContext.Current.Session["edit_upload_fileName"].ToString();
            //}
            //String newFileName = sessionUploadFileName + DateTime.Now.ToString("yyyyMMddHHmmssffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
            //String filePath = dirPath + newFileName;
            //imgFile.SaveAs(filePath);
            //String fileUrl = saveUrl + newFileName;
    
            //水印start
            String newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo);
            String filePath = dirPath + newFileName + fileExt;
            imgFile.SaveAs(filePath);
            String fileUrl = saveUrl + newFileName + fileExt;
            //添加文字水印
            Image image = System.Drawing.Image.FromFile(filePath);
            Graphics g = Graphics.FromImage(image);
            g.DrawImage(image, 0, 0, image.Width, image.Height);
            Font f = new Font("Verdana", 14);
            Brush b = new SolidBrush(Color.Red);
            string addText = "www.114390.com";
            g.DrawString(addText, f, b, 10, 10);
            g.Dispose();
            //保存加水印过后的图片,删除原始图片
            string newPath = dirPath + newFileName + "_new" + fileExt;
            image.Save(newPath);
            image.Dispose();
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
            fileUrl = saveUrl + newFileName + "_new" + fileExt;
            //水印end
            
            
            Hashtable hash = new Hashtable();
            hash["error"] = 0;
            hash["url"] = fileUrl;
            context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
            context.Response.Write(JsonMapper.ToJson(hash));
            context.Response.End();
        }
        private string getConfigAppSettings(string keyName)
        {
            if (!string.IsNullOrEmpty(keyName))
            {
                return System.Configuration.ConfigurationManager.AppSettings[keyName];
            }
            return "";
        }
        private void showError(string message)
        {
            Hashtable hash = new Hashtable();
            hash["error"] = 1;
            hash["message"] = message;
            context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
            context.Response.Write(JsonMapper.ToJson(hash));
            context.Response.End();
        }
    
        public bool IsReusable
        {
            get
            {
                return true;
            }
        }
        public bool isPic(HttpPostedFile imgFile)
        {
            int fileLen=imgFile.ContentLength;
            byte[] imgArray = new byte[fileLen];
            imgFile.InputStream.Read(imgArray, 0, fileLen);
            MemoryStream ms = new MemoryStream(imgArray);
            BinaryReader br = new BinaryReader(ms);
            string fileclass = "";
            byte buffer;
            try
            {
                buffer = br.ReadByte();
                fileclass = buffer.ToString();
                buffer = br.ReadByte();
                fileclass += buffer.ToString();
            }
            catch
            { }
            br.Close();
            ms.Close();
            //
            try
            {
                //读取上传的文件是否是图片对象,异常则删除图片
                System.Drawing.Image uploadedImg = System.Drawing.Image.FromStream(imgFile.InputStream);
                if (uploadedImg.Width < 1 || uploadedImg.Height < 1)
                {
                    return false;
                }
                uploadedImg.Dispose();
            }
            catch
            {
                return false;
            }
            //
            FileExtension[] fileEx = { FileExtension.GIF, FileExtension.BMP, FileExtension.JPG, FileExtension.PNG};
            foreach (FileExtension fe in fileEx)
            {
                try
                {
                    if (Int32.Parse(fileclass) == (int)fe)
                    {
                        if (truePic(System.Text.Encoding.ASCII.GetString(imgArray)))
                        {
                            return true;
                        }
                        return false;
                    }
                }
                catch
                { }
    
            }
            return false;
        }
        //判断上传文件中是否包含关键字
        public bool truePic(string str)
        {
            string sStr = ".getfolder|.createfolder|.deletefolder|.createdirectory|.deletedirectory|.saveas|wscript.shell|script.encode|server.|.createobject|execute|activexobject|language=|exec |insert |select |delete |update |truncate |declare |iframe |Response|Request(| Eval|Eval |Eval(|%Eval|script |using";
            string[] ck = sStr.Split('|');
            string strsql = str;
            for (int i = 0; i < ck.Length; i++)
            {
                if (str.IndexOf(ck[i]) != -1 || str.ToUpper().IndexOf(ck[i].ToUpper()) != -1)
                {
                    return false;
                }
            }
            return true;
        }
        //文件类型
        public enum FileExtension
        {
            JPG = 255216,
            GIF = 7173,
            PNG = 13780,
            BMP = 6677,
            SWF = 6787,
            SWF2 = 7087,
            RAR = 8297,
            ZIP = 8075,
            DOC = 208207,
            DOCX = 8075,
            XLS = 208207,
            XLS2 = 198243,
            XLSX = 8075,
            //_7Z = 55122,
            // 255216 jpg;   
            // 7173 gif;   
            // 6677 bmp,   
            // 13780 png;   
            // 6787 swf   
            // 7790 exe dll,   
            // 8297 rar   
            // 8075 zip   
            // 55122 7z   
            // 6063 xml   
            // 6033 html   
            // 239187 aspx   
            // 117115 cs   
            // 119105 js   
            // 102100 txt   
            // 255254 sql  
            /*
            DOC = 208207,
            DOCX = 8075,
            XLS = 208207,
            XLSX = 8075,
            JS = 239187,
            TXT = 7067,
            MP3 = 7368,
            WMA = 4838,
            MID = 7784,
            */
        }
    }
  • 相关阅读:
    C# Log4.Net日志组件的应用系列(二)
    C# Log4.Net日志组件的应用系列(一)
    使用TFS+GIT实现分布式项目管理
    动软代码生成器使用教程
    SVN使用教程
    windows系统重装流程
    使用纯真IP库获取用户端地理位置信息
    使用扩展方法重写.NET底层架构
    使用单例模式创建模型仓储层的唯一调用
    使用SQL Delta.v5.1.1.98.破解版同步数据结构
  • 原文地址:https://www.cnblogs.com/webapi/p/5669145.html
Copyright © 2011-2022 走看看