博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
kindeditor编辑器图片水印
阅读量:5097 次
发布时间:2019-06-13

本文共 8554 字,大约阅读时间需要 28 分钟。

//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("上传文件扩展名是不允许的扩展名。\n只允许" + ((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,        */    }}

 

转载于:https://www.cnblogs.com/zhaozi/p/5616228.html

你可能感兴趣的文章
mysql基础语句
查看>>
Oracle中的rownum不能使用大于>的问题
查看>>
[Data Structure & Algorithm] 有向无环图的拓扑排序及关键路径
查看>>
cassandra vs mongo (1)存储引擎
查看>>
Visual Studio基于CMake配置opencv1.0.0、opencv2.2
查看>>
Vue音乐项目笔记(三)
查看>>
遍历Map对象
查看>>
计算剪贴板里仿制的代码行数
查看>>
MySQL索引背后的数据结构及算法原理
查看>>
#Leetcode# 209. Minimum Size Subarray Sum
查看>>
SDN第四次作业
查看>>
DM8168 DVRRDK软件框架研究
查看>>
django迁移数据库错误
查看>>
yii 跳转页面
查看>>
洛谷 1449——后缀表达式(线性数据结构)
查看>>
[最小割][Kruskal] Luogu P5039 最小生成树
查看>>
Data truncation: Out of range value for column 'Quality' at row 1
查看>>
Dirichlet分布深入理解
查看>>
(转)Android之发送短信的两种方式
查看>>
python第九天课程:遇到了金角大王
查看>>