以一个小项目为例:

验证码:

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. Delphi 中的哈希表(二)—— TStringHash

    unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms ...

  2. Delphi Application.MessageBox详解

    引数:1. Text:要显示的讯息2. Caption:讯息视窗的标题列文字3. Flags:讯息旗标     3.1. 可指定讯息视窗上的图示     3.2. 可指定讯息视窗出现的按钮     3 ...

  3. 【转】const 是左结合的,若左边为空,则再向右结合

    const 是左结合的,若左边为空,则再向右结合 一.指向  const  对象的指针指向  const  对象的指针,指的是指针指向的对象的内容是const的,不可修改,但指针本身(即指针的值)是可 ...

  4. myeclipse调式与属性显示

    最近做项目的时候发现一个奇怪的东西,当我用myeclipse调式时,调式窗口显示实体user所关联的role的对象属性是空的,但是,从syst打印出来是有的,最近感到很奇怪,后来发现这只是调式的一种显 ...

  5. Android源码剖析之Framework层进阶版(Wms窗口管理)

    本文来自http://blog.csdn.net/liuxian13183/ ,引用必须注明出处! 上一篇我们主要讲了Ams,篇幅有限,本篇再讲讲Wms,即WindowManagerService,管 ...

  6. IOS事件处理机制(关于触发者和响应者的确认)

    事件处理机制 在iOS中发生触摸后,事件会加入到UIApplication事件队列(在这个系列关于iOS开发的第一篇文章中我们分析iOS程序原理的时候就说过程序运行后UIApplication会循环监 ...

  7. mysql基本sql语句大全(基础用语篇)

    1.说明:创建数据库 CREATE DATABASE database-name 2.说明:删除数据库 drop database dbname 3.说明:备份sql server --- 创建 备份 ...

  8. 20145211 《Java程序设计》实验报告三:敏捷开发与XP实践

    实验内容 使用 git上传代码 使用 git相互更改代码 实现代码的重载 XP基础 XP核心实践 相关工具 一.git上传代码 这一部分是与我的partner合作的,详见他的博客- 20145326蔡 ...

  9. css3 transition属性变化与animation动画的相似性以及不同点

    下面列子中的2个图片的效果. http://zqtest.e-horse.cn/DongXueImportedCar/assets/mouseOverAnimate.html 第一个为transiti ...

  10. Selenium2学习-031-WebUI自动化实战实例-029-JavaScript 在 Selenium 自动化中的应用实例之四(获取元素位置和大小)

    通过 JS 或 JQuery 获取到元素后,通过 offsetLeft.offsetTop.offsetWidth.offsetHeight 即可获得元素的位置和大小,非常的简单,直接上源码了,敬请参 ...