1.水印的实现
a.首先创建handler类,并配置handler的配置文件
public void ProcessRequest(HttpContext context)
{
//获取图片路径
string uri = context.Request.PhysicalPath;
//制作画板
Bitmap bitmap = new Bitmap(uri);
Graphics gra = Graphics.FromImage(bitmap);
//在图片上制作水印
gra.DrawString("xxx", new Font("楷书", 20, FontStyle.Bold), Brushes.Red, new Point(700, 800));
//关闭
gra.Flush();
//保存画板
bitmap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
context.Response.WriteFile(uri);
}
b.实现图
2.验证码的实现功能
private Random RandomSeed = new Random();
public void ProcessRequest(HttpContext context)
{
获取图片路径
//string uri = context.Request.PhysicalPath;
//Bitmap bitmap = new Bitmap(uri);
//Graphics gra = Graphics.FromImage(bitmap);
//gra.DrawString("xxx", new Font("楷书", 20, FontStyle.Bold), Brushes.Red, new Point(700, 800));
//gra.Flush();
//bitmap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
//context.Response.WriteFile(uri);
string strWord = "23456789qwertyuiopasdfghjklzxcvbnm";
string NumStr = null;
for (int i = 0; i < 4; i++)
{
NumStr += strWord[RandomSeed.Next(0, strWord.Length)];
}
context.Session["vcode"] = NumStr.ToLower();
CreateImages(context, NumStr);
}
private void CreateImages(HttpContext context,string checkCode)
{
int iwidth = (int)(checkCode.Length * 13);
Bitmap image = new Bitmap(iwidth, 22);
Graphics g = Graphics.FromImage(image);
g.Clear(Color.White);
Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
string[] font = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" };
Random rand = new Random();
for(int i = 0; i < 50; i++)
{
int x = rand.Next(image.Width);
int y = rand.Next(image.Height);
g.DrawRectangle(new Pen(Color.LightGray,0),x,y,1,1);
}
for(int i = 0; i < checkCode.Length; i++)
{
int cindex = rand.Next(7);
int findex = rand.Next(5);
Font f = new Font(font[findex], 10, FontStyle.Bold);
Brush b = new SolidBrush(c[cindex]);
int ii = 4;
if ((i + 1) % 2 == 0)
{
ii = 2;
}
g.DrawString(checkCode.Substring(i, 1), f, b, 2 + (i * 12), ii);
}
g.DrawRectangle(new Pen(ColorTranslator.FromHtml("#cccccc"), 0), 0, 0, image.Width - 1, image.Height - 1);
MemoryStream ms = new MemoryStream();
image.Save(ms, ImageFormat.Jpeg);
context.Response.ClearContent();
context.Response.ContentType = "images/gif";
context.Response.BinaryWrite(ms.ToArray());
g.Dispose();
image.Dispose();
context.Response.BinaryWrite(ms.ToArray());
g.Dispose();
image.Dispose();
}