验证码
1 namespace CZBK.TestProject.Common 2 { 3 public class ValidateCode 4 { 5 public ValidateCode() 6 { 7 } 8 /// <summary> 9 /// 验证码的最大长度 10 /// </summary> 11 public int MaxLength 12 { 13 get { return 10; } 14 } 15 /// <summary> 16 /// 验证码的最小长度 17 /// </summary> 18 public int MinLength 19 { 20 get { return 1; } 21 } 22 /// <summary> 23 /// 生成验证码 24 /// </summary> 25 /// <param name="length">指定验证码的长度</param> 26 /// <returns></returns> 27 public string CreateValidateCode(int length) 28 { 29 int[] randMembers = new int[length]; 30 int[] validateNums = new int[length]; 31 string validateNumberStr = ""; 32 //生成起始序列值 33 int seekSeek = unchecked((int)DateTime.Now.Ticks); 34 Random seekRand = new Random(seekSeek); 35 int beginSeek = (int)seekRand.Next(0, Int32.MaxValue - length * 10000); 36 int[] seeks = new int[length]; 37 for (int i = 0; i < length; i++) 38 { 39 beginSeek += 10000; 40 seeks[i] = beginSeek; 41 } 42 //生成随机数字 43 for (int i = 0; i < length; i++) 44 { 45 Random rand = new Random(seeks[i]); 46 int pownum = 1 * (int)Math.Pow(10, length); 47 randMembers[i] = rand.Next(pownum, Int32.MaxValue); 48 } 49 //抽取随机数字 50 for (int i = 0; i < length; i++) 51 { 52 string numStr = randMembers[i].ToString(); 53 int numLength = numStr.Length; 54 Random rand = new Random(); 55 int numPosition = rand.Next(0, numLength - 1); 56 validateNums[i] = Int32.Parse(numStr.Substring(numPosition, 1)); 57 } 58 //生成验证码 59 for (int i = 0; i < length; i++) 60 { 61 validateNumberStr += validateNums[i].ToString(); 62 } 63 return validateNumberStr; 64 } 65 66 /// <summary> 67 /// 创建验证码的图片 68 /// </summary> 69 /// <param name="containsPage">要输出到的page对象</param> 70 /// <param name="validateNum">验证码</param> 71 public void CreateValidateGraphic(string validateCode, HttpContext context) 72 { 73 Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 12.0), 22); 74 Graphics g = Graphics.FromImage(image); 75 try 76 { 77 //生成随机生成器 78 Random random = new Random(); 79 //清空图片背景色 80 g.Clear(Color.White); 81 //画图片的干扰线 82 for (int i = 0; i < 25; i++) 83 { 84 int x1 = random.Next(image.Width); 85 int x2 = random.Next(image.Width); 86 int y1 = random.Next(image.Height); 87 int y2 = random.Next(image.Height); 88 g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2); 89 } 90 Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic)); 91 LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), 92 Color.Blue, Color.DarkRed, 1.2f, true); 93 g.DrawString(validateCode, font, brush, 3, 2); 94 //画图片的前景干扰点 95 for (int i = 0; i < 100; i++) 96 { 97 int x = random.Next(image.Width); 98 int y = random.Next(image.Height); 99 image.SetPixel(x, y, Color.FromArgb(random.Next())); 100 } 101 //画图片的边框线 102 g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1); 103 //保存图片数据 104 MemoryStream stream = new MemoryStream(); 105 image.Save(stream, ImageFormat.Jpeg); 106 //输出图片流 107 context.Response.Clear(); 108 context.Response.ContentType = "image/jpeg"; 109 context.Response.BinaryWrite(stream.ToArray()); 110 } 111 finally 112 { 113 g.Dispose(); 114 image.Dispose(); 115 } 116 } 117 /// <summary> 118 /// 得到验证码图片的长度 119 /// </summary> 120 /// <param name="validateNumLength">验证码的长度</param> 121 /// <returns></returns> 122 public static int GetImageWidth(int validateNumLength) 123 { 124 return (int)(validateNumLength * 12.0); 125 } 126 /// <summary> 127 /// 得到验证码的高度 128 /// </summary> 129 /// <returns></returns> 130 public static double GetImageHeight() 131 { 132 return 22.5; 133 } 134 } 135 }
生成缩略图
public class ImageHelper { #region 缩略图 /// <summary> /// 生成缩略图 /// </summary> /// <param name="originalImagePath">源图路径(物理路径)</param> /// <param name="thumbnailPath">缩略图路径(物理路径)</param> /// <param name="width">缩略图宽度</param> /// <param name="height">缩略图高度</param> /// <param name="mode">生成缩略图的方式</param> public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode) { System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath); int towidth = width; int toheight = height; int x = 0; int y = 0; int ow = originalImage.Width; int oh = originalImage.Height; switch (mode) { case "HW": //指定高宽缩放(可能变形) break; case "W": //指定宽,高按比例 toheight = originalImage.Height * width / originalImage.Width; break; case "H": //指定高,宽按比例 towidth = originalImage.Width * height / originalImage.Height; break; case "Cut": //指定高宽裁减(不变形) if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight) { oh = originalImage.Height; ow = originalImage.Height * towidth / toheight; y = 0; x = (originalImage.Width - ow) / 2; } else { ow = originalImage.Width; oh = originalImage.Width * height / towidth; x = 0; y = (originalImage.Height - oh) / 2; } break; default: break; } //新建一个bmp图片 System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight); //新建一个画板 System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap); //设置高质量插值法 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //设置高质量,低速度呈现平滑程度 g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //清空画布并以透明背景色填充 g.Clear(System.Drawing.Color.Transparent); //在指定位置并且按指定大小绘制原图片的指定部分 g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel); try { //以jpg格式保存缩略图 bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg); } catch (System.Exception e) { throw e; } finally { originalImage.Dispose(); bitmap.Dispose(); g.Dispose(); } } #endregion }
水印图
1 public void ProcessRequest(HttpContext context) 2 { 3 //生成水印图 4 context.Response.ContentType = "text/plain"; 5 //访问该页面创建一张图片,并且该图片上写字. 6 using (Bitmap map = new Bitmap(300, 400))//创建了一个画布 7 { 8 using (Graphics g = Graphics.FromImage(map))//为画布创建了一个画笔 9 { 10 g.Clear(Color.Azure); 11 g.DrawString("传智播客", new Font("黑体", 14.0f, FontStyle.Bold), Brushes.Red, new PointF(80,90)); 12 string fileName = Guid.NewGuid().ToString(); 13 map.Save(context.Request.MapPath("/ImagePath/"+fileName+".jpg"),System.Drawing.Imaging.ImageFormat.Jpeg);//保存图片. 14 } 15 } 16 }
文件下载
1 public void ProcessRequest(HttpContext context) 2 { 3 context.Response.ContentType = "text/plain"; 4 string encodeFileName = "aaa.txt"; 5 context.Response.AddHeader("Content-Disposition", string.Format("attachment;filename=\"{0}\"", encodeFileName));//在响应头中加上Content-Disposition,attachment表示以附件形式下载. 6 context.Response.WriteFile("aaa.txt"); 7 }
文件上传
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; HttpPostedFile file=context.Request.Files["fileUp"];//接收文件数据. if (file == null) { context.Response.Write("请选择文件!!"); } else { //判断上传的文件的类型. string fileName= Path.GetFileName(file.FileName);//获取文件名与扩张名. aa.jpg string fileExt = Path.GetExtension(fileName);//获取扩展名. if (fileExt == ".jpg"||fileExt==".gif") { string dir = "/ImagePath/"+DateTime.Now.Year+"/"+DateTime.Now.Month+"/"+DateTime.Now.Day+"/"; //创建文件夹. Directory.CreateDirectory(Path.GetDirectoryName(context.Request.MapPath(dir))); //需要对上传的文件进行重命名. string newfileName = Guid.NewGuid().ToString(); string fullDir = dir + newfileName + fileExt;//构建了完整文件路径. // file.SaveAs(context.Request.MapPath(fullDir)); // file.SaveAs(context.Request.MapPath("/ImagePath/"+fileName));//保存文件 using (Image imge = Image.FromStream(file.InputStream))//根据上传的文件流创建Image { using (Bitmap map = new Bitmap(imge.Width,imge.Height)) { using (Graphics g = Graphics.FromImage(map)) { //设置高质量插值法 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //设置高质量,低速度呈现平滑程度 g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //先将图片画到画布上. g.DrawImage(imge, new Rectangle(0, 0, imge.Width, imge.Height)); //在右下角添加水印. g.DrawString("传智播客", new Font("黑体", 14.0f, FontStyle.Bold), Brushes.Red, new PointF(imge.Width-100,imge.Height-30)); map.Save(context.Request.MapPath(fullDir),System.Drawing.Imaging.ImageFormat.Jpeg); } } } context.Response.Write("<html><head></head><body><img src=‘"+fullDir+"‘/></body></html>"); //最后将上传成功的图片的路径存储到数据库。 } else { context.Response.Write("文件类型错误!!"); } } }
时间: 2024-10-05 00:10:05