System.Drawing.Image tempimage = System.Drawing.Image.FromStream(imgFile.InputStream, true); int imagewidth = tempimage.Width;//宽 int imageheight = tempimage.Height;//高 DateTime now = DateTime.Now; //计算文件的保存文件夹下 //用年/月/日做文件目录,这样避免一个文件夹下文件过多问题 //用文件的MD5值做文件名,这样避免多次上传同一副图片造成磁盘浪费 string fileName = "/Upload/" + now.Year + "/" + now.Month + "/" + now.Day + "/" + CommonHelper.CalcMD5(imgFile.FileName) + fileExt; imgFile.InputStream.Position = 0; string imgFileFullPath = Server.MapPath("~" + fileName); System.IO.Directory.CreateDirectory(Path.GetDirectoryName(imgFileFullPath));//如果文件夹不存在,则先创建文件夹 imageUrl = fileName; if (imagewidth > 500 || imageheight > 600) { byte[] bytes = WebHelper.CreateImg(tempimage, imageheight * 1.0 / imagewidth);
using (Stream outStream = new FileStream(Server.MapPath(imageUrl), FileMode.Create)) { outStream.Write(bytes, 0, bytes.Length);//类似于GetString } } else { imgFile.SaveAs(imgFileFullPath); }
/// <summary> /// 生成一个验证码图片 /// </summary> /// <param name="validCode">生成的验证码</param> /// <returns>图片的JPEG格式的二进制数据</returns> public static byte[] CreateImg(System.Drawing.Image imgOutput, double hw) { //常用汉字 using (Bitmap bmp = new Bitmap(500, Convert.ToInt32(500 * hw))) using (Graphics g = Graphics.FromImage(bmp)) using (MemoryStream ms = new MemoryStream()) { g.Clear(Color.White); //修改成80×80大小 System.Drawing.Image imgOutput2 = imgOutput.GetThumbnailImage(500, Convert.ToInt32(500 * hw), null, IntPtr.Zero); g.DrawImage(imgOutput2, 0, 0); Random rand = new Random(); bmp.Save(ms, ImageFormat.Jpeg); ms.Position = 0; return ms.ToArray(); } }