ASP.NET的一般处理程序对图片文件的基本操作

以一个小项目为例:

验证码:

ASP.NET的一般处理程序对图片文件的基本操作
public class VerifyCodeHelper
{
    public VerifyCodeHelper()
    {
        this.ran = new Random();
    }

    private Random ran = null;
    private string verifyCode;
    /// <summary>
    /// 验证码
    /// </summary>
    public string VerifyCode
    {
        get { return verifyCode; }
        set { verifyCode = value; }
    }


    /// <summary>
    /// 获取验证码图片对象
    /// </summary>
    /// <returns>System.Drawing.Image </returns>
    public System.Drawing.Image GetVerifyCode()
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder(5);
        System.Drawing.Image img = new System.Drawing.Bitmap(105, 50);//验证码图片大小

        using (System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(img))//取材
        {
            int sp = this.GetNumber(1, 3, true);
            graphics.FillRectangle(System.Drawing.Brushes.White, 0, 0, img.Width, img.Height);//填方
            graphics.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Silver), 0, 0, img.Width - 1, img.Height - 1);//画方
            for (int i = 1; i < 5; i++)//5个字符
            {
                using (System.Drawing.Brush b = new System.Drawing.SolidBrush(System.Drawing.Color.FromName(this.GetColorName())))//彩色画刷
                {
                    string c = string.Empty;
                    sb.Append((c = this.GetChar().ToString()));
                    System.Drawing.PointF pf = this.GetPointF(sp, sp + 6, -5, 2);//由于字体的关系Point不准了,又是字符会出界,已经排除了一些字体了
                    System.Drawing.Font f = this.GetFont(34, 41);
                    //画字符
                    graphics.DrawString(c, f, b, pf);//位置要一次间隔向后
                    sp += this.GetNumber(16, 20, true);
                }
                using (System.Drawing.Brush b = new System.Drawing.SolidBrush(System.Drawing.Color.FromName(this.GetColorName())))//彩色画刷
                {
                    //画点:位置随即了
                    for (int j = 1; j <= this.GetNumber(8, 16, true); j++)
                    {
                        graphics.DrawString(".",
                            new System.Drawing.Font(this.GetFontName(), this.GetNumber(6, 8, true)), b,
                            this.GetPointF(1, 99, 1, 39));
                    }
                }
                using (System.Drawing.Brush b = new System.Drawing.SolidBrush(System.Drawing.Color.FromName(this.GetColorName())))//彩色画刷
                {
                    //画线:位置随即了
                    graphics.DrawLine(
                        new System.Drawing.Pen(b, this.GetNumber(1, 2, true)),
                        this.GetPointF(1, 99, 1, 39), this.GetPointF(1, 99, 1, 39));
                }
            }
        }
        this.verifyCode = sb.ToString();
        return img;
    }
    /// <summary>
    /// 
    /// </summary>
    /// <returns>FontName</returns>
    private string GetFontName()
    {
        System.Collections.Generic.List<string> Not = new System.Collections.Generic.List<string>();
        string[] not = { "BatangChe", "DotumChe", "GulimChe", "GungsuhChe", "Angsana New", "AngsanaUPC", "Arabic Typesetting",
                           "Browallia New", "BrowalliaUPC", "Cordia New", "CordiaUPC", "DaunPenh", "DilleniaUPC", "EucrosiaUPC",
                           "FreesiaUPC", "Gabriola","IrisUPC", "JasmineUPC","KodchiangUPC", "Kokila","LilyUPC", "Microsoft Himalaya",
                           "Microsoft Uighur", "Microsoft Yi Baiti","MoolBoran", "Nyala","Sakkal Majalla", "Segoe Script","Shonar Bangla",
                           "Utsaah","Wingdings","Cambria Math","Narkisim","Batang","Lucida Console","MT Extra","Dotum","Marlett",
                       "Mangal","Malgun Gothic","Segoe Print","Lucida Sans Unicode","DokChampa","Webdings","Latha","MV Boli"};
        Not.AddRange(not);
        System.Collections.Generic.List<string> FontNames = new System.Collections.Generic.List<string>();
        foreach (System.Drawing.FontFamily item in System.Drawing.FontFamily.Families)
        {
            if (!Not.Contains(item.Name))
                FontNames.Add(item.Name);
        }
        return FontNames[this.GetNumber(1, FontNames.Count - 1, true)];
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="xmin"></param>
    /// <param name="xmax"></param>
    /// <param name="ymin"></param>
    /// <param name="ymax"></param>
    /// <returns>PointF</returns>
    private System.Drawing.PointF GetPointF(int xmin, int xmax, int ymin, int ymax)
    {
        return new System.Drawing.PointF(this.GetNumber(xmin, xmax, true), this.GetNumber(ymin, ymax, true));
    }
    /// <summary>
    /// 
    /// </summary>
    /// <returns>char</returns>
    private char GetChar()
    {
        char[] charItems = {0,1,2,3,4,5,6,7,8,9,
                               a,b,c,d,e,f,g,h,i,j,k,l,m,
                               n,o,p,q,r,s,t,u,v,w,x,y,z,
                               A,B,C,D,E,F,G,H,I,J,K,L,M,
                               N,O,P,Q,R,S,T,U,V,W,X,Y,Z };
        return charItems[this.GetNumber(0, charItems.Length - 1, true)];
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="min"></param>
    /// <param name="max"></param>
    /// <returns>Font</returns>
    private System.Drawing.Font GetFont(int min, int max)
    {
        return new System.Drawing.Font(
            this.GetFontName(),
            this.GetNumber(min, max, true),
            (System.Drawing.FontStyle)this.GetNumber(0, 2, true),
            System.Drawing.GraphicsUnit.Pixel);
    }
    /// <summary>
    /// 
    /// </summary>
    /// <returns>ColorName</returns>
    private string GetColorName()
    {
        string[] names ={ "Aqua","Black","Blue","BlueViolet","Brown",
                          "Crimson","DarkBlue","DarkGreen","DarkMagenta","DarkOliveGreen",
                          "DarkOrange","DarkOrchid","DarkRed","DarkSlateBlue",
                          "DarkTurquoise","DarkViolet","DeepPink","DeepSkyBlue",
                          "Firebrick","Green","Indigo","LightGreen","Magenta",
                          "MediumBlue","Maroon","Navy","OrangeRed","Purple",
                          "Red","RoyalBlue","Salmon","SeaGreen","Sienna","SlateBlue","Violet"};
        return names[this.GetNumber(0, names.Length - 1, true)];
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="min"></param>
    /// <param name="max"></param>
    /// <param name="isContinue"></param>
    /// <returns>int</returns>
    private int GetNumber(int min, int max, bool isContinue)
    {
        int a;
        while (!isContinue)
            if ((a = ran.Next(min, max + 1) % 2) == 0)
                return a;
        return ran.Next(min, max + 1);
    }
}
ASP.NET的一般处理程序对图片文件的基本操作

ashx文件:

ASP.NET的一般处理程序对图片文件的基本操作
<%@ WebHandler Language="C#" Class="VerifyCode" %>

using System;
using System.Web;

public class VerifyCode : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        if (context.Request.UrlReferrer != null)
        {
            VerifyCodeHelper vc = new VerifyCodeHelper();
            using (System.Drawing.Image img = vc.GetVerifyCode())
            {
                img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            }

            context.Response.SetCookie(new HttpCookie("code", vc.VerifyCode));
            //context.Session["code"] = vc.VerifyCode;}
        }
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}
ASP.NET的一般处理程序对图片文件的基本操作

html调用:

ASP.NET的一般处理程序对图片文件的基本操作
  验证码:<input type="text" name="txtCode" id="txtCode" /><img id="img" title="点击切换验证码" alt="验证码" src="VerifyCode.ashx" onclick="this.src=‘VerifyCode.ashx?ran=‘+new Date();" /><br />
ASP.NET的一般处理程序对图片文件的基本操作

上传文件:

ASP.NET的一般处理程序对图片文件的基本操作
<%@ WebHandler Language="C#" Class="Upload" %>

using System;
using System.Web;
using System.Web.SessionState;
public class Upload : IHttpHandler, IRequiresSessionState
{
    private BLL.TransferAction transfer = null;
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/html";
        if (context.Session["name"] != null)
        {
            if (context.Request.Url.Query == "?ID=" + context.Session["IDCard"])
            {
                HttpPostedFile uploadFile = context.Request.Files["txtUpload"];

                if (uploadFile.ContentLength > 0 && uploadFile.ContentType.IndexOf("image") > -1)
                {
                    //百度浏览器下只取了名字+后缀
                    string fileName = System.IO.Path.GetFileName(uploadFile.FileName);
                    //上传图片名称
                    string imgName = context.Session["IDCard"] + fileName.Substring(fileName.Length - 4);
                    //存到网站路径
                    uploadFile.SaveAs(context.Server.MapPath(context.Session["OImg"].ToString()));
                    //临时Session  小图片路径名称
                    string imgSName = "s" + imgName;
                    context.Session["imgSPath"] = "Upload/" + imgSName;
                    //生成小图
                    using (System.Drawing.Image img = ImageHelper.GetSImg(context.Server.MapPath("Upload/" + imgName)))
                    {
                        img.Save(context.Server.MapPath(context.Session["imgSPath"].ToString()));
                    }
                    transfer = new BLL.TransferAction();
                    //存入数据库URL
                    if (transfer.Update(context.Session["IDCard"].ToString(), context.Session["imgSPath"].ToString()) == 1)
                    {
                        InfoHelper.Identity.PortraitURL = context.Session["imgSPath"].ToString();
                        context.Response.Write("文件:" + fileName + "保存成功。<div style=\"color:Red;size:25px;width:30px;height:30px;\" id=\"Info\">3</div><script>var sec=3;setInterval(function(){if(sec>0){document.getElementById(‘Info‘).innerHTML=sec;sec--;}else{window.location=‘MyInfoList.ashx‘;}},1000);</script>" + "秒后跳转。");
                    }
                    else
                    {
                        context.Response.Write("文件:" + fileName + "保存失败。");
                    }
                }
            }
            else
            {
                string con = IOHelper.CreateInstance(context).GetFileContent("Upload.html");
                context.Response.Write(con.Replace("XXXXXX", context.Session["IDCard"].ToString()));
            }
        }
        else
            context.Response.Redirect("HomePage.html");
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}
ASP.NET的一般处理程序对图片文件的基本操作

html文件:

ASP.NET的一般处理程序对图片文件的基本操作
<body>
    <form action="Upload.ashx?ID=XXXXXX" method="post" enctype="multipart/form-data">
        <input type="file" name="txtUpload"  />
        <input type="submit" value="上传" />
    </form>
</body
ASP.NET的一般处理程序对图片文件的基本操作

下载文件:

ASP.NET的一般处理程序对图片文件的基本操作
<%@ WebHandler Language="C#" Class="DownLoad" %>

using System;
using System.Web;

public class DownLoad : IHttpHandler,System.Web.SessionState.IRequiresSessionState
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/html";
        if (context.Session["name"] != null && context.Request.Url.ToString().Contains("DownLoad.ashx"))
        {            
            context.Response.AddHeader("Content-Disposition", "attachment;filename="+context.Request.QueryString["filename"]);
            context.Response.WriteFile(context.Server.MapPath(context.Session["IdentityCard"].ToString()));
        }
        else
            context.Response.Redirect("HomePage.html");
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}
ASP.NET的一般处理程序对图片文件的基本操作

html:

ASP.NET的一般处理程序对图片文件的基本操作
string contextY = "<img src=\"" + context.Session["IdentityCard"].ToString() + "\" alt=\"" + context.Session["name"].ToString() + "\"/><br/><a href=‘DownLoad.ashx?filename=\"" + context.Session["IdentityCard"].ToString() + "\"‘>下载</a>
ASP.NET的一般处理程序对图片文件的基本操作

相关项目文件:http://pan.baidu.com/s/1eQmopOm

ASP.NET的一般处理程序对图片文件的基本操作,布布扣,bubuko.com

ASP.NET的一般处理程序对图片文件的基本操作

上一篇:JSP内置对象及作用


下一篇:lvgl 视频叠加图标显示