以一个小项目为例:

验证码:

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. Structured Streaming Programming Guide

    https://spark.apache.org/docs/latest/structured-streaming-programming-guide.html http://www.slidesha ...

  2. 应用github pages创建自己的个人博客

    首先你需要注册自己的github账号 1.登录或者注册github,登录之后点击右上角的“+”号,选择“New repository”菜单,创建仓库,用于存储和博客相关的源文件. 2.跳转页面将填写域 ...

  3. 在windows下创建一个Mongo服务

    首先需要下载mongo的安装包 cmd.exe 这个需要用管理员权限打开 进入到mongo的安装目录 首先到C盘根据下面的命令手动创建一个 Data 文件夹 在Data 里面创建一个db文件夹一个lo ...

  4. HBase的架构以及各个模块的功能

    一:整体架构 1.体系结构 2.物理模型 3.存储体系 regionserver->region->多个store(列簇)->一个memstore和多个storefile 4.HDF ...

  5. Prism&MEF构建开发框架

    系统框架构想效果图 平台简单由左侧菜单和右侧内容区以及顶部系统和用户信息区构成 菜单根据系统模块动态加载 右侧,根据左侧选中菜单动态加载子模块,子模块集合以tab选项卡方式布局 系统模块划分为Shel ...

  6. HTML与CSS的关系

    1. HTML是网页内容的载体.内容就是网页制作者放在页面上想要让用户浏览的信息,可以包含文字.图片.视频等. 2. CSS样式是表现.就像网页的外衣.比如,标题字体.颜色变化,或为标题加入背景图片. ...

  7. [LeetCode]题解(python):104 Maximum Depth of Binary Tree

    题目来源 https://leetcode.com/problems/maximum-depth-of-binary-tree/ Given a binary tree, find its maxim ...

  8. UITableViewCell 设置圆角

    #import <QuartzCore/QuartzCore.h> QuartzCore.framework [self.commentsCell.layer setMasksToBoun ...

  9. 面向对象世界里转转七(Liskov替换原则)

    前言:Liskov替换原则是关于继承机制的应用原则,是实现开放封闭原则的具体规范,违反了Liskov原则必然意味着违反了开放封闭原则.因此,有必要对面向对象的继承机制及其基本原则做以探索,来进一步了解 ...

  10. documentElement和ownerDocument和ownerElement

    1.document.documentElement是指文档根节点----HTML元素 2.element.ownerDocument是指当前元素所在的文档对象----document 3.attrO ...