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();
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的一般处理程序对图片文件的基本操作的更多相关文章
- ASP.NET学习笔记 —— 一般处理程序之图片上传
简单图片上传功能目标:实现从本地磁盘读取图片文件,展示到浏览器页面.步骤:(1). 首先创建一个用于上传图片的HTML模板,命名为ImageUpload.html: <!DOCTYPE html ...
- EF+LINQ事物处理 C# 使用NLog记录日志入门操作 ASP.NET MVC多语言 仿微软网站效果(转) 详解C#特性和反射(一) c# API接受图片文件以Base64格式上传图片 .NET读取json数据并绑定到对象
EF+LINQ事物处理 在使用EF的情况下,怎么进行事务的处理,来减少数据操作时的失误,比如重复插入数据等等这些问题,这都是经常会遇到的一些问题 但是如果是我有多个站点,然后存在同类型的角色去操作 ...
- Asp.net图片文件上传
对课本上的代码进行了一点的优化 1.获取文件的名称和文件的后缀名 引用了System.IO, 用Path.GetFileNamehe()取得文件名和Path.GetExtension获取文件的后缀 2 ...
- Asp.net web服务处理程序(第六篇)
四.Web服务处理程序 对于Web服务来说,标准的方式是使用SOAP协议,在SOAP中,请求和回应的数据通过XML格式进行描述.在Asp.net 4.0下,对于Web服务来说,还可以选择支持Ajax访 ...
- ASP.NET ASHX 一般处理程序教程
你不想创建一个普通ASP.NET的Web窗体页.而又要通过一个查询字符串返回一个动态的图片.XML或者非HTML网页.这是一个用C#编程语言编写的使用ASHX(一般处理程序)的简单教程. 简介 首先, ...
- Asp.Net Mvc 使用WebUploader 多图片上传
来博客园有一个月了,哈哈.在这里学到了很多东西.今天也来试着分享一下学到的东西.希望能和大家做朋友共同进步. 最近由于项目需要上传多张图片,对于我这只菜鸟来说,以前上传图片都是直接拖得控件啊,而且还是 ...
- [深入浅出WP8.1(Runtime)]生成图片和存储生成的图片文件
7.2.3 使用RenderTargetBitmap类生成图片 RenderTargetBitmap类可以将可视化对象转换为位图,也就是说它可以将任意的UIElement以位图的形式呈现.那么我们在实 ...
- paip.解决中文url路径的问题图片文件不能显示
paip.解决中文url路径的问题图片文件不能显示 #现状..中文url路径 图片文件不能显示 <img src="img/QQ截图20140401175433.jpg" w ...
- asp.net动态输出透明gif图片
要使用asp.net动态输出透明gif图片,也就是用Response.ContentType = "image/GIF". 查了国内几个中文资料都没解决,最后是在一个英文博客上找到 ...
随机推荐
- Apache Kafka源码分析 - PartitionStateMachine
startup 在onControllerFailover中被调用, initializePartitionState private def initializePartitionState() { ...
- PureBasic 读取文件中一行的两个数据例子
, "Test1.txt") ; if the file could be read, we continue... , "Test2.txt") ) = ; ...
- Python - 求斐波那契数列前N项之和
n = int(input("Input N: ")) a = 0 b = 1 sum = 0 for i in range(n): sum += a a, b = b, a + ...
- linux ntp时间同步
linux ntp时间同步 一.搭建时间同步服务器1.编译安装ntp serverrpm -qa | grep ntp若没有找到,则说明没有安装ntp包,从光盘上找到ntp包,使用rpm -Uvh n ...
- ORACLE FormBuilder触发器执行顺序
1.当打开FORM时: (1)PRE-FORM (2)PRE-BLOCK(BLOCK级) (3)WHEN-NEW-FORM-INSTANCE (4)WHEN-NEW-BLOCK-INSTANCE (5 ...
- yii多数据库
Yii中同时连接多个数据库 Published by 荒野无灯 on 2011-07-09 02:12:45 under PHP/Yii Tags:yii,database 14162 views 0 ...
- 初入C的世界
大家好,我叫吉贯之,来自贵州省遵义市,现就读于北京工业大学耿丹学院信息技术系计算机与科学专业,我的学号是160809127,我喜欢运动和一些电脑方面的软件操作. 应老师要求在博客园建立的博客,地址是h ...
- NRF51822之动态广播使用
本教程基于nRF51_SDK_10.0.0_dc26b5e\examples\ble_peripheral\ble_app_uart工程 本教程主要是演示 现在演示通过nus来修改ADV中maufac ...
- Activity初步,初学者必看
Activity是什么? Activity是一个可与用户交互并呈现组件的视图.通俗说就是运行的程序当前的这个显示界面. 如果你还不明白,那么你写过HTML吗,它就好比一个网页.我们程序中的用户视图,都 ...
- <q>标签,短文本引用;<blockquote>标签,长文本引用
<q>标签,短文本引用 <q>引用文本</q>,默认显示双引号,不需要在文本中添加 <blockquote>标签,长文本引用 浏览器对<block ...