以一个小项目为例:

验证码:

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();
System.Drawing.Image img = new System.Drawing.Bitmap(, );//验证码图片大小 using (System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(img))//取材
{
int sp = this.GetNumber(, , true);
graphics.FillRectangle(System.Drawing.Brushes.White, , , img.Width, img.Height);//填方
graphics.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Silver), , , img.Width - , img.Height - );//画方
for (int i = ; i < ; 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 + , -, );//由于字体的关系Point不准了,又是字符会出界,已经排除了一些字体了
System.Drawing.Font f = this.GetFont(, );
//画字符
graphics.DrawString(c, f, b, pf);//位置要一次间隔向后
sp += this.GetNumber(, , true);
}
using (System.Drawing.Brush b = new System.Drawing.SolidBrush(System.Drawing.Color.FromName(this.GetColorName())))//彩色画刷
{
//画点:位置随即了
for (int j = ; j <= this.GetNumber(, , true); j++)
{
graphics.DrawString(".",
new System.Drawing.Font(this.GetFontName(), this.GetNumber(, , true)), b,
this.GetPointF(, , , ));
}
}
using (System.Drawing.Brush b = new System.Drawing.SolidBrush(System.Drawing.Color.FromName(this.GetColorName())))//彩色画刷
{
//画线:位置随即了
graphics.DrawLine(
new System.Drawing.Pen(b, this.GetNumber(, , true)),
this.GetPointF(, , , ), this.GetPointF(, , , ));
}
}
}
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(, FontNames.Count - , 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 = {'','','','','','','','','','',
'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(, charItems.Length - , 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(, , 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(, names.Length - , 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 + ) % ) == )
return a;
return ran.Next(min, max + );
}
}

ashx文件:

<%@ 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;
}
}
}

html调用:

  验证码:<input type="text" name="txtCode" id="txtCode" /><img id="img" title="点击切换验证码" alt="验证码" src="VerifyCode.ashx" onclick="this.src='VerifyCode.ashx?ran='+new Date();" /><br />

上传文件:

<%@ 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 > && uploadFile.ContentType.IndexOf("image") > -)
{
//百度浏览器下只取了名字+后缀
string fileName = System.IO.Path.GetFileName(uploadFile.FileName);
//上传图片名称
string imgName = context.Session["IDCard"] + fileName.Substring(fileName.Length - );
//存到网站路径
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()) == )
{
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;
}
} }

html文件:

<body>
<form action="Upload.ashx?ID=XXXXXX" method="post" enctype="multipart/form-data">
<input type="file" name="txtUpload" />
<input type="submit" value="上传" />
</form>
</body

下载文件:

<%@ 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;
}
} }

html:

string contextY = "<img src=\"" + context.Session["IdentityCard"].ToString() + "\" alt=\"" + context.Session["name"].ToString() + "\"/><br/><a href='DownLoad.ashx?filename=\"" + context.Session["IdentityCard"].ToString() + "\"'>下载</a>

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

ASP.NET的一般处理程序对图片文件的基本操作的更多相关文章

  1. ASP.NET学习笔记 —— 一般处理程序之图片上传

    简单图片上传功能目标:实现从本地磁盘读取图片文件,展示到浏览器页面.步骤:(1). 首先创建一个用于上传图片的HTML模板,命名为ImageUpload.html: <!DOCTYPE html ...

  2. EF+LINQ事物处理 C# 使用NLog记录日志入门操作 ASP.NET MVC多语言 仿微软网站效果(转) 详解C#特性和反射(一) c# API接受图片文件以Base64格式上传图片 .NET读取json数据并绑定到对象

    EF+LINQ事物处理   在使用EF的情况下,怎么进行事务的处理,来减少数据操作时的失误,比如重复插入数据等等这些问题,这都是经常会遇到的一些问题 但是如果是我有多个站点,然后存在同类型的角色去操作 ...

  3. Asp.net图片文件上传

    对课本上的代码进行了一点的优化 1.获取文件的名称和文件的后缀名 引用了System.IO, 用Path.GetFileNamehe()取得文件名和Path.GetExtension获取文件的后缀 2 ...

  4. Asp.net web服务处理程序(第六篇)

    四.Web服务处理程序 对于Web服务来说,标准的方式是使用SOAP协议,在SOAP中,请求和回应的数据通过XML格式进行描述.在Asp.net 4.0下,对于Web服务来说,还可以选择支持Ajax访 ...

  5. ASP.NET ASHX 一般处理程序教程

    你不想创建一个普通ASP.NET的Web窗体页.而又要通过一个查询字符串返回一个动态的图片.XML或者非HTML网页.这是一个用C#编程语言编写的使用ASHX(一般处理程序)的简单教程. 简介 首先, ...

  6. Asp.Net Mvc 使用WebUploader 多图片上传

    来博客园有一个月了,哈哈.在这里学到了很多东西.今天也来试着分享一下学到的东西.希望能和大家做朋友共同进步. 最近由于项目需要上传多张图片,对于我这只菜鸟来说,以前上传图片都是直接拖得控件啊,而且还是 ...

  7. [深入浅出WP8.1(Runtime)]生成图片和存储生成的图片文件

    7.2.3 使用RenderTargetBitmap类生成图片 RenderTargetBitmap类可以将可视化对象转换为位图,也就是说它可以将任意的UIElement以位图的形式呈现.那么我们在实 ...

  8. paip.解决中文url路径的问题图片文件不能显示

    paip.解决中文url路径的问题图片文件不能显示 #现状..中文url路径 图片文件不能显示 <img src="img/QQ截图20140401175433.jpg" w ...

  9. asp.net动态输出透明gif图片

    要使用asp.net动态输出透明gif图片,也就是用Response.ContentType = "image/GIF". 查了国内几个中文资料都没解决,最后是在一个英文博客上找到 ...

随机推荐

  1. ubuntu12.04 安装 php5.4/php5.5

    1:修改源(我使用163的源)直接修改/etc/apt/sources.list deb http://mirrors.163.com/ubuntu/ precise main universe re ...

  2. CC2541连接BTool教程

    一.简介 本篇介绍如何基于Smart RF(主芯片CC2541).Smart RF(主芯片CC2540).Usb Dongle,来使用软件BTool. 本篇暂时只介绍如何连接,不介绍如何使用BTool ...

  3. 设计模式:简单工厂(Simple Factory)

    定义:根据提供的数据或参数返回几种可能类中的一种. 示例:实现计算器功能,要求输入两个数和运算符号,得到结果. 结构图: HTML: <html xmlns="http://www.w ...

  4. css3 loading效果

    file:///E:/zhangqiangWork/2014/SPDbank/index.html 参考该网站 http://tobiasahlin.com/spinkit/ 查看源代码把里面的dom ...

  5. python StringIO

    模块是用类编写的,只有一个StringIO类,所以它的可用方法都在类中. 此类中的大部分函数都与对文件的操作方法类似. 例: 复制代码 代码如下: #coding=gbk   import Strin ...

  6. Java学习-025-类名或方法名应用之一 -- 调试源码

    上文讲述了如何获取类名和方法名,敬请参阅: Java学习-024-获取当前类名或方法名二三文 . 通常在应用开发中,调试或查看是哪个文件中的方法调用了当前文件的此方法,因而在实际的应用中需要获取相应的 ...

  7. c# 并行运算

    c# 并行运算 1. Parallel.INVOKE() 看实例: private static Stopwatch watch = new Stopwatch(); private static v ...

  8. JS实现动画原理一(闭包方式)

    前提:      你必须了解js的闭包(否则你看不懂滴)     我们就来做一个js实现jq animate的动画效果来简单探索一下,js动画实现的简单原理: html代码 <div id=&q ...

  9. js获取框架(IFrame)的内容

    <frameset id="fr" rows="50%,50%">      <frame name="up" id=&q ...

  10. 线上Linux服务器运维安全策略经验分享

    线上Linux服务器运维安全策略经验分享 https://mp.weixin.qq.com/s?__biz=MjM5NTU2MTQwNA==&mid=402022683&idx=1&a ...