net 生成gif动画验证码
用ServletJSP动态生成图像验证码

用ServletJSP动态生成图像验证码现在有不少网站在用户填写表单时,同时要求填写验证码,验证码的一个目的就是防范一些恶意的网站下载软件,这些软件能通过遍历链接而将网站的所有网页下载。
还可以防止用户不经过本网站的页面而使用网站的资源。
所以现在有不少网站都使用了验证码技术,验证码通常是一个在WEB服务器上生成的随机字符串,同时以某种方式保存起来,比如保存到与当前的Session中,然后在用户提交网页时与用户输入的验证比较是否一致,然而如果直接以明文的方式,还是不能防范一些功能较强的自动填写表格的软件。
所以一般将验证码以图片的形式显示出来,同时可以将在图片中显示的字符串进行一些处理,比如使用旋转字符,添加背景纹理等技术以增大被软件识别的难度。
下面简要介绍一下如果实现这种验证码:首先实现一个servlet用来生成图片(当然也可以用jsp实现):import javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*;import com.sun.image.codec.jpeg.*;import java.awt.*;import com.sun.image.codec.jpeg.*;import java.awt.image.BufferedImage;import java.awt.image.DataBuffer;import java.awt.geom.GeneralPath;import javax.swing.*;import java.math.*;public class Servlet1extends HttpServlet {//Process the HTTP Get requestpublic void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setContentType(CONTENT_TYPE);response.setContentType("image/jpeg"); //必须设置ContentType为image/jpegint length = 4; //设置默认生成4个数字Date d = new Date();long lseed = d.getTime();java.util.Random r = new Random(lseed); //设置随机种子if (request.getParameter("length") != null) {try {length = Integer.parseInt(request.getParameter("length"));}catch (NumberFormatException e) {}}StringBuffer str = new StringBuffer();for (int i = 0; i <length; i++) {str.append(r.nextInt(9)); //生成随机数字}//可以在此加入保存验证码的代码//创建内存图像BufferedImage bi = new BufferedImage(40, 16, BufferedImage.TYPE_INT_RGB); Graphics2D g = bi.createGraphics();g.clearRect(0, 0, 16, 40);g.setColor(Color.green.CY AN);g.drawString(str.toString(), 4, 12);try {//使用JPEG编码,输出到response的输出流JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(response. getOutputStream());JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);param.setQuality(1.0f, false);encoder.setJPEGEncodeParam(param);encoder.encode(bi);}catch (Exception ex) {}}}然后在需求显示验证码的加入以下代码就可以了<img alt="" src="/WebModule1/servlet1" width="40" height="16"/>将/WebModule1/servlet1替换成你用来生成验证码的servlet的全路径。
.Net二维码验证码生成下载与识别

二维码识别与验证系统的设计与实现摘要:图像识别,是利用计算机对图像进行处理、分析和理解,以识别各种不同模式的目标和对像的技术。
验证码识别是图像数字识别的热门研究方向。
本系统以Visual Studio作为开发环境,使通过C#语言编程实现,利用网格特征模板、交叉点特征模板、改进的活动模板, 结合孔洞数特征, 设计了基于模板匹配算法的模糊数字验证码识别系统。
为进一步提高识别率, 提出了一种加权模板及其构造方案, 并运用统计学方法。
通过在线下载网络上的验证码来动态测试本系统的有效性和鲁棒性。
旨在通过获取观察对象、图像灰度化、特征提取、二值化图像、图像切割、细化、字符外形特征分析然后通过模板匹配获取结果。
论文在介绍了设计背景以及系统分析后,详述了系统总体设计、编码等过程,并对设计过程中采用的关键技术、遇到的难点问题及解决方法做了重点论述。
关键词:验证码,识别,C#Design and Implementation of a two-dimensional Code Recognition and Verification SystemAbstract:Image recognition is the technique that deals with processing ,analysis and understanding of the images by puter to identify the different mode of target. Verification code recognition is a popular research direction of digital image recognition.This system uses Visual Studio as development environment, which is realized by C# language programming.With the use of grid feature template,crossing points feature template, improved active template, bined with the hole number features, we design verification code identification system of fuzzy numbers based on template matching method.In order to further improve the recognition rate, this paper proposes a weighted template and its construction scheme,includingstatistical method. The verification code through online download on the network dynamically tests the effectiveness and robustness of the system.Aimed to obtain object of observation, the gray image, feature extraction, the two value image, image cutting, thinning, character shape feature analysis , then using the template matching gets results.This paper introduces the design background and analysis of the system, details system design, coding process, and the difficulties encountered, the key technology in the process of design and the solution is detailed.Keywords: Verification code, recognition, C#文档目录前言1第1章绪论21.1 项目背景31.2 设计原则41.3 本章小结4第2章系统分析52.1 系统分析52.1.1 系统输入输出环节需求分析62.1.2 系统算法需求分析62.1.3 系统图像处理环节需求分析62.1.4 系统功能环节需求分析62.1.5 系统菜单分类分析62.2 系统工作流程72.3 系统创新性分析82.4 本章小结8第3章总体设计83.1 系统总体体系结构83.2 二维码生成与验证系统模块总体设计93.2.1 二维码生成模块设计9文档3.2.2 二维码识别模块设计113.3 关键技术分析123.4 本章小结13第4章编码实现134.1 系统开发环境134.2 程序设计语言134.3 核心功能编码实现134.3.1 二维码生成144.4 本章小结15第5章系统测试与维护155.1 运行环境165.2 测试原则165.3 测试方法165.4 模块测试175.5 模块整合测试175.6 系统整体测试185.7 系统的运行结果185.8 系统维护20结束语21参考文献22致谢23前言当今网络社会选择加密已是我们别无选择,其一是我们知道在互联网上进行文件传输、电子商务往来存在许多不安全因素,特别是对于一些大公司和一些某某文件在网络上传输。
php生成动态图片验证码代码

php生成动态图片验证码代码php生成动态图片验证码代码php生成动态图片验证码的一段代码,有需要的朋友可以看看。
一个简单的php图形验证码程序:(产生一个随机数,取得随机字符串,然后将该字符串设置进session--方便验证;php生成动态图片验证码的.一段代码,有需要的朋友可以看看。
一个简单的php图形验证码程序:(产生一个随机数,取得随机字符串,然后将该字符串设置进session--方便验证;PHP设置成@header("Content-Type:image/png");生成对应图片。
)另外,记得把php中extension=php_gd2.dll 打开。
复制代码代码如下:<?phpsession_start();function random($len){$srCStr="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";$strs="";for($i=0;$i<$len;$i++){$strs.=$srCStr[mt_rand(0,35)];}return $strs;}$str=random(4); //随机生成的字符串$width = 50; //验证码图片的宽度$height = 25; //验证码图片的高度@header("Content-Type:image/png");$_SESSION["code"] = $str;$im = imagecreate($width,$height);//背景色$back = imagecolorallocate($im,0xFF,0xFF,0xFF);//模糊点颜色$pix = imagecolorallocate($im,187,230,247);//字体色$font = imagecolorallocate($im,41,163,238);//绘模糊作用的点for($i=0;$i<1000;$i++){imagesetpixel($im,mt_rand(0,$width),mt_rand(0,$height),$pi x);}imagestring($im, 5, 7, 5,$str, $font);imagerectangle($im,0,0,$width-1,$height-1,$font);imagepng($im);imagedestroy($im);$_SESSION["code"] = $str;>小结:自 PHP 4.2.0 起,不再需要用 srand()或 mt_srand() 函数给随机数发生器播种,现已自动完成。
Asp.net中图片验证码的设计与实现

中图片验证码的设计与实现作者:王伟娜刘群来源:《电脑知识与技术》2013年第11期摘要:图片验证码已成为许多主流网站用来防止非法用户自动注册、登录、灌水的一种有效手段。
该文在介绍了验证码原理、技术的基础上,给出了在中设计图片验证码的方法。
关键词:图片验证码;;Session中图分类号:TP311 文献标识码:A 文章编号:1009-3044(2013)11-2598-03当今的互联网环境下,基于软件的安全性防护是软件开发人员必须考虑的一个重要问题。
在传统的网站登录界面中基本上只需要填写好用户名和密码来与数据库中的用户信息进行比从而确定是否允许该用户登录,但非法用户无处不在,攻击方式和手段数不胜数,如机器人程序自动登陆、批量注册、暴力破解密码、截获用户名和密码等导致传统方式中网站安全性不高。
因此,把好系统登陆这一关极为重要,目前很多web页面采用一种安全防御技术,在登陆系统时不但要填写用户名和密码,还要输入验证码,在很大程度上增强了系统登录的安全性。
1 验证码技术介绍1.1 常见的验证码类型目前的网站中使用的验证码类型有:文本验证码、图片验证码、邮件验证码和手机验证码四大类。
文本验证码是最原始的技术,由于安全性较低,多数网站目前已经弃用这种方式;图片验证码则采用随机生成的若干数字或字母组成一张图像,然后在图像上布满杂点等干扰像素,或者是对字母数字进行旋转、变形、扭曲等操作,迫使用户用肉眼辨认出图片中的一串符号并手工输入到文本框,连同用户名和密码一起提交到服务器进行验证,三项信息全部验证成功才能登录系统;邮件验证码需要用户在网页中输入自己的电邮,系统将验证码通过邮件这种途径推送到用户邮箱中,从时间成本和工作效率来看,这种形式相对而言要麻烦些;手机验证码需要用户输入手机号码来接收网站发送的验证码信息,由于涉及到个人的电话信息,容易遭到用户的排斥,除银行等安全级别较高的服务网站外,大多数的网站不会采用这种方式。
ASP.NET实现验证码图片

实现验证码图⽚新建⼀个checkcode.aspx⽂件,页⾯中不⽤写任何东西,在代码中,Page_Load中写⼊如下代码:string chkCode = string.Empty;int ix, iy;ix = 80;iy = 24;//颜⾊列表,⽤于验证码、噪线、噪点Color[] color ={ Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.Brown, Color.DarkBlue }; //字体列表,⽤于验证码string[] font ={ "Times New Roman", "MS Mincho", "Book Antiqua", "Gungsuh", "MingLiU", "Arial" };//验证码的字符集,去掉了⼀些容易混淆的字符char[] character ={ '2', '3', '4', '5', '6', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y' };Random rnd = new Random();//⽣成验证码字符串for (int i = 0; i < 4; i++){chkCode += character[rnd.Next(character.Length)];}Bitmap bmp = new Bitmap(ix, iy);Graphics g = Graphics.FromImage(bmp);g.Clear(Color.White);//画噪线for (int i = 0; i < 10; i++){int x1 = rnd.Next(ix);int y1 = rnd.Next(iy);int x2 = rnd.Next(ix);int y2 = rnd.Next(iy);Color clr = color[rnd.Next(color.Length)];g.DrawLine(new Pen(clr), x1, y1, x2, y2);}//画验证码字符串for (int i = 0; i < chkCode.Length; i++){string fnt = font[rnd.Next(font.Length)];Font ft = new Font(fnt, 14, FontStyle.Bold);Color clr = color[rnd.Next(color.Length)];g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 16 + 2, (float)2);}//画噪点for (int i = 0; i < 50; i++){int x = rnd.Next(bmp.Width);int y = rnd.Next(bmp.Height);Color clr = color[rnd.Next(color.Length)];bmp.SetPixel(x, y, clr);}//将验证码写⼊SESSIONSession["checkcode"] = chkCode.ToLower();//清除该页输出缓存,设置该页⽆缓存Response.Buffer = true;Response.ExpiresAbsolute = System.DateTime.Now.AddMilliseconds(0);Response.Expires = 0;Response.CacheControl = "no-cache";Response.AppendHeader("Pragma", "No-Cache");//将验证码图⽚写⼊内存流,并将其以 "image/Png" 格式输出MemoryStream ms = new MemoryStream();try{bmp.Save(ms, ImageFormat.Png);Response.ClearContent();Response.ContentType = "image/Png";Response.BinaryWrite(ms.ToArray());}finally{//显式释放资源bmp.Dispose();g.Dispose();}在login.aspx中,添加Image控件,设置ImageUrl=“checkcode.aspx" 即可。
net 生成gif动画验证码

.net 生成gif动画验证码using System;using System.IO;using System.Web;using System.Drawing;//GIF验证码类public class Validate{//设置最少4位验证码private byte TrueValidateCodeCount = 4;public byte ValidateCodeCount{get { return TrueValidateCodeCount; }set{//验证码至少为3位if (value > 4)TrueValidateCodeCount = value;}}protected string ValidateCode = "";//是否消除锯齿public bool FontTextRenderingHint = false;//验证码字体public string ValidateCodeFont = "Arial";//验证码型号(像素)public float ValidateCodeSize = 13;public int ImageHeight = 23;//定义验证码中所有的字符public string AllChar = "1,2,3,4,5,6,7,8,9,0,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,W,X,Y,Z";//获得随机四位数private void CreateValidate(){ValidateCode = "";//将验证码中所有的字符保存在一个字符串数组中string[] CharArray = AllChar.Split(',');int Temp = -1;//生成一个随机对象Random RandCode = new Random();//根据验证码的位数循环for (int i = 0; i < ValidateCodeCount; i++){//主要是防止生成相同的验证码if (Temp != -1){//加入时间的刻度RandCode = new Random(i * Temp * ((int)DateTime.Now.Ticks));}int t = RandCode.Next(35);if (Temp == t){//相等的话重新生成CreateValidate();}Temp = t;ValidateCode += CharArray[Temp];}//错误检测,去除超过指定位数的验证码if (ValidateCode.Length > TrueValidateCodeCount)ValidateCode = ValidateCode.Remove(TrueValidateCodeCount);}//生成一帧的BMP图象private void CreateImageBmp(out Bitmap ImageFrame){//获得验证码字符char[] CodeCharArray = ValidateCode.ToCharArray(0, ValidateCodeCount);//图像的宽度-与验证码的长度成一定比例int ImageWidth = (int)(TrueValidateCodeCount * ValidateCodeSize * 1.3 + 4);//创建一个长20,宽iwidth的图像对象ImageFrame = new Bitmap(ImageWidth, ImageHeight);//创建一个新绘图对象Graphics ImageGraphics = Graphics.FromImage(ImageFrame);//清除背景色,并填充背景色//Note:Color.Transparent为透明ImageGraphics.Clear(Color.White);//绘图用的字体和字号Font CodeFont = new Font(ValidateCodeFont, ValidateCodeSize, FontStyle.Bold);//绘图用的刷子大小Brush ImageBrush = new SolidBrush(Color.Red);//字体高度计算int FontHeight = (int)Math.Max(ImageHeight - ValidateCodeSize - 3, 2);//创建随机对象Random rand = new Random();//开始随机安排字符的位置,并画到图像里for (int i = 0; i < TrueValidateCodeCount; i++){//生成随机点,决定字符串的开始输出范围int[] FontCoordinate = new int[2];FontCoordinate[0] = (int)(i * ValidateCodeSize + rand.Next(1)) + 3;FontCoordinate[1] = rand.Next(FontHeight);Point FontDrawPoint = new Point(FontCoordinate[0], FontCoordinate[1]);//消除锯齿操作if (FontTextRenderingHint)ImageGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel;elseImageGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;//格式化刷子属性-用指定的刷子、颜色等在指定的范围内画图ImageGraphics.DrawString(CodeCharArray[i].ToString(), CodeFont, ImageBrush, FontDrawPoint);}ImageGraphics.Dispose();}//处理生成的BMPprivate void DisposeImageBmp(ref Bitmap ImageFrame){//创建绘图对象Graphics ImageGraphics = Graphics.FromImage(ImageFrame);//创建铅笔对象Pen ImagePen = new Pen(Color.Red, 1);//创建随机对象Random rand = new Random();//创建随机点Point[] RandPoint = new Point[2];//随机画线for (int i = 0; i < 15; i++){RandPoint[0] = new Point(rand.Next(ImageFrame.Width), rand.Next(ImageFrame.Height));RandPoint[1] = new Point(rand.Next(ImageFrame.Width), rand.Next(ImageFrame.Height));ImageGraphics.DrawLine(ImagePen, RandPoint[0], RandPoint[1]);}ImageGraphics.Dispose();}//创建GIF动画private void CreateImageGif(){Bitmap ImageFrame;Kissogram.Drawing.Gif.AnimatedGifEncoder GifPic = new Kissogram.Drawing.Gif.AnimatedGifEncoder();MemoryStream BmpMemory = new MemoryStream();GifPic.Start();//确保视觉残留GifPic.SetDelay(5);//-1:no repeat,0:always repeatGifPic.SetRepeat(0);for (int i = 0; i < 20; i++){//创建一帧的图像CreateImageBmp(out ImageFrame);//生成随机线条DisposeImageBmp(ref ImageFrame);//输出绘图,将图像保存到指定的流ImageFrame.Save(BmpMemory,System.Drawing.Imaging.ImageFormat.Png);GifPic.AddFrame(Image.FromStream(BmpMemory));BmpMemory = new MemoryStream();}GifPic.OutPut(ref BmpMemory);HttpContext.Current.Response.ClearContent();//配置输出类型HttpContext.Current.Response.ContentType = "image/Gif";//输出内容HttpContext.Current.Response.BinaryWrite(BmpMemory.ToArray());BmpMemory.Close();BmpMemory.Dispose();}//输出验证码public void OutPutValidate(string ValidateCodeSession){CreateValidate();CreateImageGif();//把生成的验证码输入到SESSIONHttpContext.Current.Session[ValidateCodeSession] = ValidateCode;}}加水印的代码:public static Bitmap WaterMarkWithText(System.Drawing.Bitmap origialGif, string text,string filePath){//用于存放桢List frames = new List();//如果不是gif文件,直接返回原图像if (origialGif.RawFormat.Guid != System.Drawing.Imaging.ImageFormat.Gif.Guid){return origialGif;}//如果该图像是gif文件foreach (Guid guid in origialGif.FrameDimensionsList){System.Drawing.Imaging.FrameDimension frameDimension = new System.Drawing.Imaging.FrameDimension(guid);int frameCount = origialGif.GetFrameCount(frameDimension);for (int i = 0; i < frameCount; i++){if (origialGif.SelectActiveFrame(frameDimension, i) == 0){int delay = Convert.ToInt32(origialGif.GetPropertyItem(20736).Value.GetValue(i));Image img = Image.FromHbitmap(origialGif.GetHbitmap());Font font = new Font(new FontFamily("宋体"), 35.0f,FontStyle.Bold);Graphics g = Graphics.FromImage(img);g.DrawString(text, font, Brushes.BlanchedAlmond, new PointF(10.0f, 10.0f));Frame frame = new Frame(img, delay);frames.Add(frame);}}ponents.AnimatedGifEncoder gif = new ponents.AnimatedGifEncoder();gif.Start(filePath);gif.SetDelay(100);gif.SetRepeat(0);for (int i = 0; i < frames.Count; i++){gif.AddFrame(frames[i].Image);}gif.Finish();try{Bitmap gifImg = (Bitmap)Bitmap.FromFile(filePath);return gifImg;}catch{return origialGif;}}return origialGif;}Bitmap bmp = new Bitmap(100, 100);Graphics g = Graphics.FromImage(bmp);Font f = new Font("arial", 11f);Brush b = Brushes.Blue;string txt = "Rotate text animation!";SizeF sz = g.MeasureString(txt, f);g.Clear(Color.WhiteSmoke);g.DrawString(txt, f, b, 50-sz.Width/2, 50-sz.Height/2);g.Flush();GifImage.GifAnimation gif = new GifImage.GifAnimation(bmp,GifImage.GraphicControlExt.Default);gif.Application = GifImage.ApplicationExt.Default;eGlobalColorTableOnly = true;for (int i = 1; i < 36; ++i){g.Clear(Color.WhiteSmoke);g.TranslateTransform(50,50);g.RotateTransform(10f * i);g.DrawString(txt, f, b, sz.Width/-2, sz.Height/-2);g.ResetTransform();g.DrawString("Hello", f, Brushes.Red, -50 + i * 4, 20);g.DrawString("Yeah", f, Brushes.Orange, 60, -20+i*4);g.Flush();gif.AddFrame(bmp);}f.Dispose();g.Dispose();bmp.Dispose();FileStream fs = new FileStream(@"E:\vmlinux\out.gif", FileMode.Create); gif.Save(fs);fs.Close();Console.WriteLine("{0}x{1}", gif.Screen.Width, gif.Screen.Height);。
.net生成图片验证码

// 取得当前点的颜色
int nOldX = 0, nOldY = 0;
nOldX = bXDir ? i + (int)(dy * dMultValue) : i;
nOldY = bXDir ? j : j + (int)(dy * dMultValue);
string code=CreateVerifyCode();
CreateImageOnPage(code, context);
context.Response.Cookies.Add(new HttpCookie("CheckCode", code.ToUpper()));// 使用Cookies取验证码的值
private const double PI2 = 6.283185307179586476925286766559;
/// <summary>
/// 正弦曲线Wave扭曲图片(Edit By )
/// </summary>
dx = bXDir ? (PI2 * (double)j) / dBaseAxisLen : (PI2 * (double)i) / dBaseAxisLen;
dx += dPhase;
double dy = Math.Sin(dx);
string[] fonts = { "Arial", "Georgia" };
public string[] Fonts
{
get { return fonts; }
set { fonts = value; }
using System.Drawing.Imaging;
如何为网页设计制作动态的GIF图像

如何为网页设计制作动态的GIF图像一、概述和介绍(150字)- GIF(Graphics Interchange Format)是一种常用的图片格式,它支持动画效果,非常适合用于网页设计。
- 制作动态的GIF图像可以为网页增加吸引力和用户体验,提升页面的互动性。
二、准备工作(200字)1. 选择合适的GIF制作工具:市面上有很多GIF制作工具可供选择,如Adobe Photoshop、GIMP、Ezgif等,根据个人需求和操作习惯选择适合自己的工具。
2. 收集合适的素材:根据网页的主题和目标,收集需要在GIF中展示的素材,包括图片、短视频或动画片段等。
三、使用Adobe Photoshop制作GIF(350字)1. 打开Adobe Photoshop软件,选择“新建”创建一个新的文稿。
2. 导入素材:打开素材文件夹,将需要使用的素材拖拽到Photoshop文稿中。
3. 调整素材尺寸:使用“变换工具”或“裁剪工具”对素材进行尺寸调整,使其适应网页设计需要。
4. 配置时间轴:在Photoshop中,选择“窗口”-“时间轴”打开时间轴面板。
在时间轴中,可以添加、删除、调整素材的帧,设置每一帧的时间间隔。
5. 添加过渡效果:为了制作更流畅的GIF效果,可以在相邻帧之间添加过渡效果,如渐变、淡入淡出等。
6. 优化GIF:点击“文件”-“存储为Web用途”将GIF保存为Web格式,选择合适的压缩选项和颜色模式,减小GIF文件大小并保持画质。
四、使用GIMP制作GIF(350字)1. 打开GIMP软件,选择“文件”-“新建”创建一个新的文稿。
2. 导入素材:选择“文件”-“打开作为图层”,将需要使用的素材逐个导入到GIMP文稿中,每个素材对应一个图层。
3. 调整素材尺寸:使用“工具箱”中的工具,如放缩工具、裁剪工具等,对素材进行尺寸调整,使其适应网页设计需要。
4. 配置时间轴:选择“窗口”-“插件”-“动画”,在弹出的动画面板中,可以添加、删除、调整素材的帧,设置每一帧的时间间隔。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
.net 生成gif动画验证码using System;using System.IO;using System.Web;using System.Drawing;//GIF验证码类public class Validate{//设置最少4位验证码private byte TrueValidateCodeCount = 4;public byte ValidateCodeCount{get { return TrueValidateCodeCount; }set{//验证码至少为3位if (value > 4)TrueValidateCodeCount = value;}}protected string ValidateCode = "";//是否消除锯齿public bool FontTextRenderingHint = false;//验证码字体public string ValidateCodeFont = "Arial";//验证码型号(像素)public float ValidateCodeSize = 13;public int ImageHeight = 23;//定义验证码中所有的字符public string AllChar = "1,2,3,4,5,6,7,8,9,0,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,W,X,Y,Z";//获得随机四位数private void CreateValidate(){ValidateCode = "";//将验证码中所有的字符保存在一个字符串数组中string[] CharArray = AllChar.Split(',');int Temp = -1;//生成一个随机对象Random RandCode = new Random();//根据验证码的位数循环for (int i = 0; i < ValidateCodeCount; i++){//主要是防止生成相同的验证码if (Temp != -1){//加入时间的刻度RandCode = new Random(i * Temp * ((int)DateTime.Now.Ticks));}int t = RandCode.Next(35);if (Temp == t){//相等的话重新生成CreateValidate();}Temp = t;ValidateCode += CharArray[Temp];}//错误检测,去除超过指定位数的验证码if (ValidateCode.Length > TrueValidateCodeCount)ValidateCode = ValidateCode.Remove(TrueValidateCodeCount);}//生成一帧的BMP图象private void CreateImageBmp(out Bitmap ImageFrame){//获得验证码字符char[] CodeCharArray = ValidateCode.ToCharArray(0, ValidateCodeCount);//图像的宽度-与验证码的长度成一定比例int ImageWidth = (int)(TrueValidateCodeCount * ValidateCodeSize * 1.3 + 4);//创建一个长20,宽iwidth的图像对象ImageFrame = new Bitmap(ImageWidth, ImageHeight);//创建一个新绘图对象Graphics ImageGraphics = Graphics.FromImage(ImageFrame);//清除背景色,并填充背景色//Note:Color.Transparent为透明ImageGraphics.Clear(Color.White);//绘图用的字体和字号Font CodeFont = new Font(ValidateCodeFont, ValidateCodeSize, FontStyle.Bold);//绘图用的刷子大小Brush ImageBrush = new SolidBrush(Color.Red);//字体高度计算int FontHeight = (int)Math.Max(ImageHeight - ValidateCodeSize - 3, 2);//创建随机对象Random rand = new Random();//开始随机安排字符的位置,并画到图像里for (int i = 0; i < TrueValidateCodeCount; i++){//生成随机点,决定字符串的开始输出范围int[] FontCoordinate = new int[2];FontCoordinate[0] = (int)(i * ValidateCodeSize + rand.Next(1)) + 3;FontCoordinate[1] = rand.Next(FontHeight);Point FontDrawPoint = new Point(FontCoordinate[0], FontCoordinate[1]);//消除锯齿操作if (FontTextRenderingHint)ImageGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel;elseImageGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;//格式化刷子属性-用指定的刷子、颜色等在指定的范围内画图ImageGraphics.DrawString(CodeCharArray[i].ToString(), CodeFont, ImageBrush, FontDrawPoint);}ImageGraphics.Dispose();}//处理生成的BMPprivate void DisposeImageBmp(ref Bitmap ImageFrame){//创建绘图对象Graphics ImageGraphics = Graphics.FromImage(ImageFrame);//创建铅笔对象Pen ImagePen = new Pen(Color.Red, 1);//创建随机对象Random rand = new Random();//创建随机点Point[] RandPoint = new Point[2];//随机画线for (int i = 0; i < 15; i++){RandPoint[0] = new Point(rand.Next(ImageFrame.Width), rand.Next(ImageFrame.Height));RandPoint[1] = new Point(rand.Next(ImageFrame.Width), rand.Next(ImageFrame.Height));ImageGraphics.DrawLine(ImagePen, RandPoint[0], RandPoint[1]);}ImageGraphics.Dispose();}//创建GIF动画private void CreateImageGif(){Bitmap ImageFrame;Kissogram.Drawing.Gif.AnimatedGifEncoder GifPic = new Kissogram.Drawing.Gif.AnimatedGifEncoder();MemoryStream BmpMemory = new MemoryStream();GifPic.Start();//确保视觉残留GifPic.SetDelay(5);//-1:no repeat,0:always repeatGifPic.SetRepeat(0);for (int i = 0; i < 20; i++){//创建一帧的图像CreateImageBmp(out ImageFrame);//生成随机线条DisposeImageBmp(ref ImageFrame);//输出绘图,将图像保存到指定的流ImageFrame.Save(BmpMemory,System.Drawing.Imaging.ImageFormat.Png);GifPic.AddFrame(Image.FromStream(BmpMemory));BmpMemory = new MemoryStream();}GifPic.OutPut(ref BmpMemory);HttpContext.Current.Response.ClearContent();//配置输出类型HttpContext.Current.Response.ContentType = "image/Gif";//输出内容HttpContext.Current.Response.BinaryWrite(BmpMemory.ToArray());BmpMemory.Close();BmpMemory.Dispose();}//输出验证码public void OutPutValidate(string ValidateCodeSession){CreateValidate();CreateImageGif();//把生成的验证码输入到SESSIONHttpContext.Current.Session[ValidateCodeSession] = ValidateCode;}}加水印的代码:public static Bitmap WaterMarkWithText(System.Drawing.Bitmap origialGif, string text,string filePath){//用于存放桢List frames = new List();//如果不是gif文件,直接返回原图像if (origialGif.RawFormat.Guid != System.Drawing.Imaging.ImageFormat.Gif.Guid){return origialGif;}//如果该图像是gif文件foreach (Guid guid in origialGif.FrameDimensionsList){System.Drawing.Imaging.FrameDimension frameDimension = new System.Drawing.Imaging.FrameDimension(guid);int frameCount = origialGif.GetFrameCount(frameDimension);for (int i = 0; i < frameCount; i++){if (origialGif.SelectActiveFrame(frameDimension, i) == 0){int delay = Convert.ToInt32(origialGif.GetPropertyItem(20736).Value.GetValue(i));Image img = Image.FromHbitmap(origialGif.GetHbitmap());Font font = new Font(new FontFamily("宋体"), 35.0f,FontStyle.Bold);Graphics g = Graphics.FromImage(img);g.DrawString(text, font, Brushes.BlanchedAlmond, new PointF(10.0f, 10.0f));Frame frame = new Frame(img, delay);frames.Add(frame);}}ponents.AnimatedGifEncoder gif = new ponents.AnimatedGifEncoder();gif.Start(filePath);gif.SetDelay(100);gif.SetRepeat(0);for (int i = 0; i < frames.Count; i++){gif.AddFrame(frames[i].Image);}gif.Finish();try{Bitmap gifImg = (Bitmap)Bitmap.FromFile(filePath);return gifImg;}catch{return origialGif;}}return origialGif;}Bitmap bmp = new Bitmap(100, 100);Graphics g = Graphics.FromImage(bmp);Font f = new Font("arial", 11f);Brush b = Brushes.Blue;string txt = "Rotate text animation!";SizeF sz = g.MeasureString(txt, f);g.Clear(Color.WhiteSmoke);g.DrawString(txt, f, b, 50-sz.Width/2, 50-sz.Height/2);g.Flush();GifImage.GifAnimation gif = new GifImage.GifAnimation(bmp,GifImage.GraphicControlExt.Default);gif.Application = GifImage.ApplicationExt.Default;eGlobalColorTableOnly = true;for (int i = 1; i < 36; ++i){g.Clear(Color.WhiteSmoke);g.TranslateTransform(50,50);g.RotateTransform(10f * i);g.DrawString(txt, f, b, sz.Width/-2, sz.Height/-2);g.ResetTransform();g.DrawString("Hello", f, Brushes.Red, -50 + i * 4, 20);g.DrawString("Yeah", f, Brushes.Orange, 60, -20+i*4);g.Flush();gif.AddFrame(bmp);}f.Dispose();g.Dispose();bmp.Dispose();FileStream fs = new FileStream(@"E:\vmlinux\out.gif", FileMode.Create); gif.Save(fs);fs.Close();Console.WriteLine("{0}x{1}", gif.Screen.Width, gif.Screen.Height);。