C# 上传文件
有个博友问多个文件上传的问题,正好最近我也遇见这样的问题,刚好解决,费了好大的劲儿呀!终于皇天不负有心人啊,写到上边也让自己记住,希望这对那位博友有所帮助吧,也希望各位大牛看到后提出意见。大家互相学习,共同努力,加油!好了废话不多说了,开始吧,上例子。
View Code
1 1.最简单的单文件上传(没花头) 2 3 效果图: 4 5 说明:这是最基本的文件上传,在asp.Net1.x中没有这个FileUpload控件,只有html的上传控件,那时候要把html控件转化为服务器控件,很不好用。其实所有文件上传的美丽效果都是从这个FileUpload控件衍生,第一个例子虽然简单却是根本。 6 7 后台代码: 8 using System; 9 using System.Data; 10 using System.Configuration; 11 using System.Collections; 12 using System.Web; 13 using System.Web.Security; 14 using System.Web.UI; 15 using System.Web.UI.WebControls; 16 using System.Web.UI.WebControls.WebParts; 17 using System.Web.UI.HtmlControls; 18 19 public partial class _Default : System.Web.UI.Page 20 { 21 protected void Page_Load(object sender, EventArgs e) 22 { 23 24 } 25 protected void bt_upload_Click(object sender, EventArgs e) 26 { 27 try 28 { 29 if (FileUpload1.PostedFile.FileName == "") 30 { 31 this.lb_info.Text = "请选择文件!"; 32 } 33 else 34 { 35 string filepath = FileUpload1.PostedFile.FileName; 36 string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1); 37 string serverpath = Server.MapPath("images/") + filename; 38 FileUpload1.PostedFile.SaveAs(serverpath); 39 this.lb_info.Text = "上传成功!"; 40 } 41 } 42 catch (Exception ex) 43 { 44 this.lb_info.Text = "上传发生错误!原因是:" + ex.ToString(); 45 } 46 } 47 } 48 49 前台代码: 50 <table style="width: 343px"> 51 <tr> 52 <td style="width: 100px"> 53 单文件上传</td> 54 <td style="width: 100px"> 55 </td> 56 </tr> 57 <tr> 58 <td style="width: 100px"> 59 <asp:FileUpload ID="FileUpload1" runat="server" Width="475px" /> 60 </td> 61 <td style="width: 100px"> 62 <asp:Button ID="bt_upload" runat="server" OnClick="bt_upload_Click" Text="上传" /></td> 63 </tr> 64 <tr> 65 <td style="width: 100px; height: 21px;"> 66 <asp:Label ID="lb_info" runat="server" ForeColor="Red" Width="183px"></asp:Label></td> 67 <td style="width: 100px; height: 21px"> 68 </td> 69 </tr> 70 </table> 71 72 2.多文件上传 73 74 效果图: 75 76 77 后台代码: 78 using System; 79 using System.Data; 80 using System.Configuration; 81 using System.Collections; 82 using System.Web; 83 using System.Web.Security; 84 using System.Web.UI; 85 using System.Web.UI.WebControls; 86 using System.Web.UI.WebControls.WebParts; 87 using System.Web.UI.HtmlControls; 88 89 public partial class _Default : System.Web.UI.Page 90 { 91 protected void Page_Load(object sender, EventArgs e) 92 { 93 94 } 95 protected void bt_upload_Click(object sender, EventArgs e) 96 { 97 98 if ((FileUpload1.PostedFile.FileName == "" && FileUpload2.PostedFile.FileName == "")&&FileUpload3.PostedFile.FileName == "") 99 { 100 this.lb_info.Text = "请选择文件!"; 101 } 102 else 103 { 104 HttpFileCollection myfiles = Request.Files; 105 for (int i = 0; i < myfiles.Count; i++) 106 { 107 HttpPostedFile mypost = myfiles[i]; 108 try 109 { 110 if (mypost.ContentLength > 0) 111 { 112 string filepath = mypost.FileName; 113 string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1); 114 string serverpath = Server.MapPath("images/") + filename; 115 mypost.SaveAs(serverpath); 116 this.lb_info.Text = "上传成功!"; 117 } 118 } 119 catch (Exception error) 120 { 121 this.lb_info.Text = "上传发生错误!原因:" + error.ToString(); 122 } 123 124 } 125 126 } 127 } 128 129 } 130 131 前台代码: 132 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> 133 134 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 135 136 <html Xmlns="http://www.w3.org/1999/xhtml" > 137 <head runat="server"> 138 <title>多文件上传 清清月儿http://blog.csdn.Net/21as.Net/</title> 139 </head> 140 <body> 141 <form id="form1" runat="server"> 142 <div> 143 <table style="width: 343px"> 144 <tr> 145 <td style="width: 100px"> 146 多文件上传</td> 147 <td style="width: 100px"> 148 </td> 149 </tr> 150 <tr> 151 <td style="width: 100px"> 152 <asp:FileUpload ID="FileUpload1" runat="server" Width="475px" /> 153 </td> 154 <td style="width: 100px"> 155 </td> 156 </tr> 157 <tr> 158 <td style="width: 100px"> 159 <asp:FileUpload ID="FileUpload2" runat="server" Width="475px" /></td> 160 <td style="width: 100px"> 161 </td> 162 </tr> 163 <tr> 164 <td style="width: 100px"> 165 <asp:FileUpload ID="FileUpload3" runat="server" Width="475px" /></td> 166 <td style="width: 100px"> 167 </td> 168 </tr> 169 <tr> 170 <td style="width: 100px"> 171 <asp:Button ID="bt_upload" runat="server" OnClick="bt_upload_Click" Text="一起上传" /> 172 <asp:Label ID="lb_info" runat="server" ForeColor="Red" Width="183px"></asp:Label></td> 173 <td style="width: 100px"> 174 </td> 175 </tr> 176 </table> 177 178 </div> 179 </form> 180 </body> 181 </html> 182 183 3.客户端检查上传文件类型(以上传图片为例) 184 185 效果图: 186 187 后台代码和1.最简单的单文件上传一样; 188 前台代码: 189 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> 190 191 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 192 193 <html Xmlns="http://www.w3.org/1999/xhtml" > 194 <head runat="server"> 195 <title>清清月儿 .Net/21as.Nethttp://blog.csdn.Net/21as.Net</title> 196 <script language="Javascript"> 197 function Check_FileType() 198 { 199 var str=document.getElementById("FileUpload1").value; 200 var pos = str.lastIndexOf("."); 201 var lastname = str.substring(pos,str.length) 202 if (lastname.toLowerCase()!=".jpg" && lastname.toLowerCase()!=".gif") 203 { 204 alert("您上传的文件类型为"+lastname+",图片必须为.jpg,.gif类型"); 205 return false; 206 } 207 else 208 { 209 return true; 210 } 211 } 212 </script> 213 214 </head> 215 <body> 216 <form id="form1" runat="server"> 217 <div> 218 <table style="width: 343px"> 219 <tr> 220 <td style="width: 104px"> 221 文件上传判断</td> 222 <td style="width: 100px"> 223 </td> 224 </tr> 225 <tr> 226 <td style="width: 104px"> 227 <asp:FileUpload ID="FileUpload1" runat="server" Width="400px" /> 228 </td> 229 <td style="width: 100px"> 230 <asp:Button ID="bt_upload" runat="server" OnClick="bt_upload_Click" Text="上传" OnClientClick="return Check_FileType()"/></td> 231 </tr> 232 <tr> 233 <td style="width: 104px; height: 21px;"> 234 <asp:Label ID="lb_info" runat="server" ForeColor="Red" Width="183px"></asp:Label></td> 235 <td style="width: 100px; height: 21px"> 236 </td> 237 </tr> 238 </table> 239 240 </div> 241 </form> 242 </body> 243 </html> 244 说明:点击上传时先触发客户端事件Check_FileType; 245 246 4.服务器端检查上传文件类型(以上传图片为例) 247 248 效果图: 249 250 251 后台代码: 252 using System; 253 using System.Data; 254 using System.Configuration; 255 using System.Collections; 256 using System.Web; 257 using System.Web.Security; 258 using System.Web.UI; 259 using System.Web.UI.WebControls; 260 using System.Web.UI.WebControls.WebParts; 261 using System.Web.UI.HtmlControls; 262 263 public partial class _Default : System.Web.UI.Page 264 { 265 protected void Page_Load(object sender, EventArgs e) 266 { 267 268 } 269 protected void bt_upload_Click(object sender, EventArgs e) 270 { 271 try 272 { 273 if (FileUpload1.PostedFile.FileName == "") 274 { 275 this.lb_info.Text = "请选择文件!"; 276 } 277 else 278 { 279 string filepath = FileUpload1.PostedFile.FileName; 280 if (IsAllowedExtension(FileUpload1) == true) 281 { 282 283 string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1); 284 string serverpath = Server.MapPath("images/") + filename; 285 FileUpload1.PostedFile.SaveAs(serverpath); 286 this.lb_info.Text = "上传成功!"; 287 } 288 else 289 { 290 this.lb_info.Text = "请上传图片"; 291 } 292 } 293 } 294 catch (Exception error) 295 { 296 this.lb_info.Text = "上传发生错误!原因:" + error.ToString(); 297 } 298 } 299 public static bool IsAllowedExtension(FileUpload hifile) 300 { 301 string strOldFilePath = "", strExtension = ""; 302 string[] arrExtension = { ".gif", ".jpg", ".jpeg", ".bmp", ".png" }; 303 if (hifile.PostedFile.FileName != string.Empty) 304 { 305 strOldFilePath = hifile.PostedFile.FileName; 306 strExtension = strOldFilePath.Substring(strOldFilePath.LastIndexOf(".")); 307 for (int i = 0; i < arrExtension.Length; i++) 308 { 309 if (strExtension.Equals(arrExtension[i])) 310 { 311 return true; 312 } 313 } 314 } 315 return false; 316 } 317 318 } 319 320 321 5.服务器端检查上传文件类型(可以检测真正文件名) 322 其实方法4并不好,因为用户可以把XXX.txt伪装为XXX.jpg。 323 324 效果图: 325 326 327 后台代码: 328 using System; 329 using System.Data; 330 using System.Configuration; 331 using System.Collections; 332 using System.Web; 333 using System.Web.Security; 334 using System.Web.UI; 335 using System.Web.UI.WebControls; 336 using System.Web.UI.WebControls.WebParts; 337 using System.Web.UI.HtmlControls; 338 339 public partial class _Default : System.Web.UI.Page 340 { 341 //清清月儿 http://blog.csdn.Net/21as.Net 342 protected void Page_Load(object sender, EventArgs e) 343 { 344 345 } 346 protected void bt_upload_Click(object sender, EventArgs e) 347 { 348 try 349 { 350 if (FileUpload1.PostedFile.FileName == "") 351 { 352 this.lb_info.Text = "请选择文件!"; 353 } 354 else 355 { 356 string filepath = FileUpload1.PostedFile.FileName; 357 if (IsAllowedExtension(FileUpload1) == true) 358 { 359 string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1); 360 string serverpath = Server.MapPath("images/") + filename; 361 FileUpload1.PostedFile.SaveAs(serverpath); 362 this.lb_info.Text = "上传成功!"; 363 } 364 else 365 { 366 this.lb_info.Text = "请上传图片"; 367 } 368 } 369 } 370 catch (Exception error) 371 { 372 this.lb_info.Text = "上传发生错误!原因:" + error.ToString(); 373 } 374 } 375 public static bool IsAllowedExtension(FileUpload hifile) 376 { 377 System.IO.FileStream fs = new System.IO.FileStream(hifile.PostedFile.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read); 378 System.IO.BinaryReader r = new System.IO.BinaryReader(fs); 379 string fileclass = ""; 380 byte buffer; 381 try 382 { 383 buffer = r.ReadByte(); 384 fileclass = buffer.ToString(); 385 buffer = r.ReadByte(); 386 fileclass += buffer.ToString(); 387 388 } 389 catch 390 { 391 392 } 393 r.Close(); 394 fs.Close(); 395 if (fileclass == "255216" || fileclass == "7173")//说明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar 396 { 397 return true; 398 } 399 else 400 { 401 return false; 402 } 403 404 } 405 406 } 407 408 6.上传文件文件名唯一性处理(时间戳+SessionID) 409 410 效果图: 411 412 说明:年月日时分秒+临时session+原文件名 如果大家怕还会重复可以加GUID 413 后台代码: 414 415 416 try 417 { 418 if (FileUpload1.PostedFile.FileName == "") 419 { 420 this.lb_info.Text = "请选择文件!"; 421 } 422 else 423 { 424 string filepath = FileUpload1.PostedFile.FileName; 425 string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1); 426 string serverpath = Server.MapPath("images/") + System.DateTime.Now.ToString("yyy-MM-dd-hh-mm-ss") + Session.SessionID + filename; 427 FileUpload1.PostedFile.SaveAs(serverpath); 428 this.lb_info.Text = "上传成功!"; 429 } 430 } 431 catch (Exception error) 432 { 433 this.lb_info.Text = "上传发生错误!原因:" + error.ToString(); 434 } 435 436 注:GUID的方法:Guid myGuid=Guid.NewGuid(); 437 438 7.上传图片生成等比例缩略图 439 440 效果图: 441 442 443 缩略图代码: 444 ImageThumbnail.cs 445 using System; 446 using System.IO; 447 using System.Drawing; 448 using System.Drawing.Imaging; 449 450 public class ImageThumbnail 451 { 452 public Image ResourceImage; 453 private int ImageWidth; 454 private int ImageHeight; 455 public string ErrorMessage; 456 457 public ImageThumbnail(string ImageFileName) 458 { 459 ResourceImage = Image.FromFile(ImageFileName); 460 ErrorMessage = ""; 461 } 462 463 public bool ThumbnailCallback() 464 { 465 return false; 466 } 467 468 469 // 方法1,按大小 470 public bool ReducedImage(int Width, int Height, string targetFilePath) 471 { 472 try 473 { 474 Image ReducedImage; 475 Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(ThumbnailCallback); 476 ReducedImage = ResourceImage.GetThumbnailImage(Width, Height, callb, IntPtr.Zero); 477 ReducedImage.Save(@targetFilePath, ImageFormat.Jpeg); 478 ReducedImage.Dispose(); 479 return true; 480 } 481 catch (Exception e) 482 { 483 ErrorMessage = e.Message; 484 return false; 485 } 486 } 487 488 489 // 方法2,按百分比 缩小60% Percent为0.6 targetFilePath为目标路径 490 public bool ReducedImage(double Percent, string targetFilePath) 491 { 492 try 493 { 494 Image ReducedImage; 495 Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(ThumbnailCallback); 496 ImageWidth = Convert.ToInt32(ResourceImage.Width * Percent); 497 ImageHeight = (ResourceImage.Height)*ImageWidth/ ResourceImage.Width;//等比例缩放 498 ReducedImage = ResourceImage.GetThumbnailImage(ImageWidth, ImageHeight, callb, IntPtr.Zero); 499 ReducedImage.Save(@targetFilePath, ImageFormat.Jpeg); 500 ReducedImage.Dispose(); 501 return true; 502 } 503 catch (Exception e) 504 { 505 ErrorMessage = e.Message; 506 return false; 507 } 508 } 509 510 511 } 512 513 后台代码: 514 using System; 515 using System.Data; 516 using System.Configuration; 517 using System.Collections; 518 using System.Web; 519 using System.Web.Security; 520 using System.Web.UI; 521 using System.Web.UI.WebControls; 522 using System.Web.UI.WebControls.WebParts; 523 using System.Web.UI.HtmlControls; 524 public partial class _Default : System.Web.UI.Page 525 { 526 527 protected void Page_Load(object sender, EventArgs e) 528 { 529 530 } 531 protected void bt_upload_Click(object sender, EventArgs e) 532 { 533 try 534 { 535 if (FileUpload1.PostedFile.FileName == "") 536 { 537 this.lb_info.Text = "请选择文件!"; 538 } 539 else 540 { 541 string filepath = FileUpload1.PostedFile.FileName; 542 string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1); 543 string serverpath1 = Server.MapPath("images/") + filename; 544 string serverpath2 = Server.MapPath("images/") + System.DateTime.Now.ToString("yyy-MM-dd-hh-mm-ss") + Session.SessionID + filename; 545 FileUpload1.PostedFile.SaveAs(serverpath1); 546 ImageThumbnail img = new ImageThumbnail(filepath); 547 img.ReducedImage(0.4, serverpath2);//0.4表示缩小40% 548 this.lb_info.Text = "上传成功!"; 549 } 550 } 551 catch (Exception error) 552 { 553 this.lb_info.Text = "上传发生错误!原因:" + error.ToString(); 554 } 555 } 556 557 558 } 559 560 8.上传图片加水印(文字水印,图片水印,文字+图片水印) 561 562 效果图: 563 原图 564 565 水印 566 567 给图片加水印以后(注意右上角+正下方) 568 569 570 代码: 571 DrawImg.cs 出自http://www.codeproject.com/csharp/watermark.asp 572 using System; 573 using System.Drawing; 574 using System.Drawing.Imaging; 575 using System.Drawing.Drawing2D; 576 public class DrawImg 577 { 578 private string WorkingDirectory = string.Empty ; //路径 579 private string ImageName = string.Empty; //被处理的图片 580 private string ImageWater = string.Empty; //水印图片 581 private string FontString = string.Empty; //水印文字 582 583 584 enum DealType{NONE,WaterImage,WaterFont,DoubleDo}; //枚举命令 585 586 private DealType dealtype; 587 588 589 public DrawImg() 590 {} 591 592 public string PublicWorkingDirectory 593 { 594 get 595 { 596 return WorkingDirectory; 597 } 598 set 599 { 600 WorkingDirectory = value; 601 } 602 } 603 604 public string PublicImageName 605 { 606 get 607 { 608 return ImageName; 609 } 610 set 611 { 612 ImageName = value; 613 } 614 } 615 616 617 public string PublicImageWater 618 { 619 get 620 { 621 return ImageWater; 622 } 623 set //设置了水印图片的话说明是要水印图片效果的 624 { 625 dealtype = DealType.WaterImage; 626 ImageWater = value; 627 } 628 } 629 630 public string PublicFontString 631 { 632 get 633 { 634 return FontString; 635 } 636 set //设置了水印文字的话说明是要水印文字效果的 637 { 638 dealtype = DealType.WaterFont; 639 FontString = value; 640 } 641 } 642 643 644 645 public void DealImage() 646 { 647 IsDouble(); 648 649 switch( dealtype ) 650 { 651 case DealType.WaterFont: WriteFont(); break; 652 case DealType.WaterImage: WriteImg(); break; 653 case DealType.DoubleDo: WriteFontAndImg(); break; 654 } 655 656 } 657 658 private void IsDouble() 659 { 660 if(ImageWater+""!="" && FontString+""!="") 661 { 662 dealtype = DealType.DoubleDo; 663 } 664 } 665 666 private void WriteFont() 667 { 668 //set a working directory 669 //string WorkingDirectory = @"C:\Watermark_src\WaterPic"; 670 671 //define a string of text to use as the Copyright message 672 //string Copyright = "Copyright ?2002 - AP Photo/David Zalubowski"; 673 674 //create a image object containing the photograph to watermark 675 Image imgPhoto = Image.FromFile(WorkingDirectory + ImageName); 676 int phWidth = imgPhoto.Width; 677 int phHeight = imgPhoto.Height; 678 679 //create a Bitmap the Size of the original photograph 680 Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb); 681 682 bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution); 683 684 //load the Bitmap into a Graphics object 685 Graphics grPhoto = Graphics.FromImage(bmPhoto); 686 687 //------------------------------------------------------------ 688 //Step #1 - Insert Copyright message 689 //------------------------------------------------------------ 690 691 //Set the rendering quality for this Graphics object 692 grPhoto.SmoothingMode = SmoothingMode.AntiAlias; 693 694 //Draws the photo Image object at original size to the graphics object. 695 grPhoto.DrawImage( 696 imgPhoto, // Photo Image object 697 new Rectangle(0, 0, phWidth, phHeight), // Rectangle structure 698 0, // x-coordinate of the portion of the source image to draw. 699 0, // y-coordinate of the portion of the source image to draw. 700 phWidth, // Width of the portion of the source image to draw. 701 phHeight, // Height of the portion of the source image to draw. 702 GraphicsUnit.Pixel); // Units of measure 703 704 //------------------------------------------------------- 705 //to maximize the size of the Copyright message we will 706 //test multiple Font sizes to determine the largest posible 707 //font we can use for the width of the Photograph 708 //define an array of point sizes you would like to consider as possiblities 709 //------------------------------------------------------- 710 int[] sizes = new int[]{16,14,12,10,8,6,4}; 711 712 Font crFont = null; 713 SizeF crSize = new SizeF(); 714 715 //Loop through the defined sizes checking the length of the Copyright string 716 //If its length in pixles is less then the image width choose this Font size. 717 for (int i=0 ;i<7; i++) 718 { 719 //set a Font object to Arial (i)pt, Bold 720 //crFont = new Font("arial", sizes[i], FontStyle.Bold); 721 722 crFont = new Font("arial",sizes[i],FontStyle.Bold); 723 724 //Measure the Copyright string in this Font 725 crSize = grPhoto.MeasureString(FontString, crFont); 726 727 if((ushort)crSize.Width < (ushort)phWidth) 728 break; 729 } 730 731 //Since all photographs will have varying heights, determine a 732 //position 5% from the bottom of the image 733 int yPixlesFromBottom = (int)(phHeight *.05); 734 735 //Now that we have a point size use the Copyrights string height 736 //to determine a y-coordinate to draw the string of the photograph 737 float yPosFromBottom = ((phHeight - yPixlesFromBottom)-(crSize.Height/2)); 738 739 //Determine its x-coordinate by calculating the center of the width of the image 740 float xCenterOfImg = (phWidth/2); 741 742 //Define the text layout by setting the text alignment to centered 743 StringFormat StrFormat = new StringFormat(); 744 StrFormat.Alignment = StringAlignment.Center; 745 746 //define a Brush which is semi trasparent black (Alpha set to 153) 747 SolidBrush semiTransBrush2 = new SolidBrush(Color.FromArgb(153, 0, 0, 0)); 748 749 //Draw the Copyright string 750 grPhoto.DrawString(FontString, //string of text 751 crFont, //font 752 semiTransBrush2, //Brush 753 new PointF(xCenterOfImg+1,yPosFromBottom+1), //Position 754 StrFormat); 755 756 //define a Brush which is semi trasparent white (Alpha set to 153) 757 SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(153, 255, 255, 255)); 758 759 //Draw the Copyright string a second time to create a shadow effect 760 //Make sure to move this text 1 pixel to the right and down 1 pixel 761 grPhoto.DrawString(FontString, //string of text 762 crFont, &nb, sp; //font 763 semiTransBrush, //Brush 764 new PointF(xCenterOfImg,yPosFromBottom), //Position 765 StrFormat); 766 767 imgPhoto = bmPhoto; 768 grPhoto.Dispose(); 769 770 //save new image to file system. 771 imgPhoto.Save(WorkingDirectory + ImageName + "_finally.jpg", ImageFormat.Jpeg); 772 imgPhoto.Dispose(); 773 774 //Text alignment 775 } 776 777 778 private void WriteImg() 779 { 780 //set a working directory 781 //string WorkingDirectory = @"C:\Watermark_src\WaterPic"; 782 783 //create a image object containing the photograph to watermark 784 Image imgPhoto = Image.FromFile(WorkingDirectory + ImageName); 785 int phWidth = imgPhoto.Width; 786 int phHeight = imgPhoto.Height; 787 788 //create a Bitmap the Size of the original photograph 789 Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb); 790 791 bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution); 792 793 //load the Bitmap into a Graphics object 794 Graphics grPhoto = Graphics.FromImage(bmPhoto); 795 796 //create a image object containing the watermark 797 Image imgWatermark = new Bitmap(WorkingDirectory + ImageWater); 798 int wmWidth = imgWatermark.Width; 799 int wmHeight = imgWatermark.Height; 800 801 //Set the rendering quality for this Graphics object 802 grPhoto.SmoothingMode = SmoothingMode.AntiAlias; 803 804 //Draws the photo Image object at original size to the graphics object. 805 grPhoto.DrawImage( 806 imgPhoto, // Photo Image object 807 new Rectangle(0, 0, phWidth, phHeight), // Rectangle structure 808 0, // x-coordinate of the portion of the source image to draw. 809 0, // y-coordinate of the portion of the source image to draw. 810 phWidth, // Width of the portion of the source image to draw. 811 phHeight, // Height of the portion of the source image to draw. 812 GraphicsUnit.Pixel); // Units of measure 813 814 815 //------------------------------------------------------------ 816 //Step #2 - Insert Watermark image 817 //------------------------------------------------------------ 818 819 //Create a Bitmap based on the previously modified photograph Bitmap 820 Bitmap bmWatermark = new Bitmap(bmPhoto); 821 bmWatermark.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution); 822 //Load this Bitmap into a new Graphic Object 823 Graphics grWatermark = Graphics.FromImage(bmWatermark); 824 825 //To achieve a transulcent watermark we will apply (2) color 826 //manipulations by defineing a ImageAttributes object and 827 //seting (2) of its properties. 828 ImageAttributes imageAttributes = new ImageAttributes(); 829 830 //The first step in manipulating the watermark image is to replace 831 //the background color with one that is trasparent (Alpha=0, R=0, G=0, B=0) 832 //to do this we will use a Colormap and use this to define a RemapTable 833 ColorMap colorMap = new ColorMap(); 834 835 //My watermark was defined with a background of 100% Green this will 836 //be the color we search for and replace with transparency 837 colorMap.OldColor = Color.FromArgb(255, 0, 255, 0); 838 colorMap.NewColor = Color.FromArgb(0, 0, 0, 0); 839 840 ColorMap[] remapTable = {colorMap}; 841 842 imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap); 843 844 //The second color manipulation is used to change the opacity of the 845 //watermark. This is done by applying a 5x5 matrix that contains the 846 //coordinates for the RGBA space. By setting the 3rd row and 3rd column 847 //to 0.3f we achive a level of opacity 848 float[][] colorMatrixElements = { 849 new float[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f}, 850 new float[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f}, 851 new float[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f}, 852 new float[] {0.0f, 0.0f, 0.0f, 0.3f, 0.0f}, 853 new float[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}}; 854 ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements); 855 856 imageAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, 857 ColorAdjustType.Bitmap); 858 859 //For this example we will place the watermark in the upper right 860 //hand corner of the photograph. offset down 10 pixels and to the 861 //left 10 pixles 862 863 int xPosOfWm = ((phWidth - wmWidth)-10); 864 int yPosOfWm = 10; 865 866 grWatermark.DrawImage(imgWatermark, 867 new Rectangle(xPosOfWm,yPosOfWm,wmWidth,wmHeight), //Set the detination Position 868 0, // x-coordinate of the portion of the source image to draw. 869 0, // y-coordinate of the portion of the source image to draw. 870 wmWidth, // Watermark Width 871 wmHeight, // Watermark Height 872 GraphicsUnit.Pixel, // Unit of measurment 873 imageAttributes); //ImageAttributes Object 874 875 //Replace the original photgraphs bitmap with the new Bitmap 876 imgPhoto = bmWatermark; 877 grPhoto.Dispose(); 878 grWatermark.Dispose(); 879 880 //save new image to file system. 881 imgPhoto.Save(WorkingDirectory + ImageName +"_finally.jpg", ImageFormat.Jpeg); 882 imgPhoto.Dispose(); 883 imgWatermark.Dispose(); 884 885 } 886 887 888 private void WriteFontAndImg() 889 { 890 891 //create a image object containing the photograph to watermark 892 Image imgPhoto = Image.FromFile(WorkingDirectory + ImageName); 893 int phWidth = imgPhoto.Width; 894 int phHeight = imgPhoto.Height; 895 896 //create a Bitmap the Size of the original photograph 897 Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb); 898 899 bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution); 900 901 //load the Bitmap into a Graphics object 902 Graphics grPhoto = Graphics.FromImage(bmPhoto); 903 904 //create a image object containing the watermark 905 Image imgWatermark = new Bitmap(WorkingDirectory + ImageWater); 906 int wmWidth = imgWatermark.Width; 907 int wmHeight = imgWatermark.Height; 908 909 //------------------------------------------------------------ 910 //Step #1 - Insert Copyright message 911 //------------------------------------------------------------ 912 913 //Set the rendering quality for this Graphics object 914 grPhoto.SmoothingMode = SmoothingMode.AntiAlias; 915 916 //Draws the photo Image object at original size to the graphics object. 917 grPhoto.DrawImage( 918 imgPhoto, // Photo Image object 919 new Rectangle(0, 0, phWidth, phHeight), // Rectangle structure 920 0, // x-coordinate of the portion of the source image to draw. 921 0, // y-coordinate of the portion of the source image to draw. 922 phWidth, // Width of the portion of the source image to draw. 923 phHeight, // Height of the portion of the source image to draw. 924 GraphicsUnit.Pixel); // Units of measure 925 926 //------------------------------------------------------- 927 //to maximize the size of the Copyright message we will 928 //test multiple Font sizes to determine the largest posible 929 //font we can use for the width of the Photograph 930 //define an array of point sizes you would like to consider as possiblities 931 //------------------------------------------------------- 932 int[] sizes = new int[]{16,14,12,10,8,6,4}; 933 934 Font crFont = null; 935 SizeF crSize = new SizeF(); 936 937 //Loop through the defined sizes checking the length of the Copyright string 938 //If its length in pixles is less then the image width choose this Font size. 939 for (int i=0 ;i<7; i++) 940 { 941 //set a Font object to Arial (i)pt, Bold 942 crFont = new Font("arial", sizes[i], FontStyle.Bold); 943 //Measure the Copyright string in this Font 944 crSize = grPhoto.MeasureString(FontString, crFont); 945 946 if((ushort)crSize.Width < (ushort)phWidth) 947 break; 948 } 949 950 //Since all photographs will have varying heights, determine a 951 //position 5% from the bottom of the image 952 int yPixlesFromBottom = (int)(phHeight *.05); 953 954 //Now that we have a point size use the Copyrights string height 955 //to determine a y-coordinate to draw the string of the photograph 956 float yPosFromBottom = ((phHeight - yPixlesFromBottom)-(crSize.Height/2)); 957 958 //Determine its x-coordinate by calculating the center of the width of the image 959 float xCenterOfImg = (phWidth/2); 960 961 //Define the text layout by setting the text alignment to centered 962 StringFormat StrFormat = new StringFormat(); 963 StrFormat.Alignment = StringAlignment.Center; 964 965 //define a Brush which is semi trasparent black (Alpha set to 153) 966 SolidBrush semiTransBrush2 = new SolidBrush(Color.FromArgb(153, 0, 0, 0)); 967 968 //Draw the Copyright string 969 grPhoto.DrawString(FontString, //string of text 970 crFont, //font 971 semiTransBrush2, //Brush 972 new PointF(xCenterOfImg+1,yPosFromBottom+1), //Position 973 StrFormat); 974 975 //define a Brush which is semi trasparent white (Alpha set to 153) 976 SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(153, 255, 255, 255)); 977 978 //Draw the Copyright string a second time to create a shadow effect 979 //Make sure to move this text 1 pixel to the right and down 1 pixel 980 grPhoto.DrawString(FontString, //string of text 981 crFont, //font 982 semiTransBrush, //Brush 983 new PointF(xCenterOfImg,yPosFromBottom), //Position 984 StrFormat); //Text alignment 985 986 987 988 //------------------------------------------------------------ 989 //Step #2 - Insert Watermark image 990 //------------------------------------------------------------ 991 992 //Create a Bitmap based on the previously modified photograph Bitmap 993 Bitmap bmWatermark = new Bitmap(bmPhoto); 994 bmWatermark.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution); 995 //Load this Bitmap into a new Graphic Object 996 Graphics grWatermark = Graphics.FromImage(bmWatermark); 997 998 //To achieve a transulcent watermark we will apply (2) color 999 //manipulations by defineing a ImageAttributes object and 1000 //seting (2) of its properties. 1001 ImageAttributes imageAttributes = new ImageAttributes(); 1002 1003 //The first step in manipulating the watermark image is to replace 1004 //the background color with one that is trasparent (Alpha=0, R=0, G=0, B=0) 1005 //to do this we will use a Colormap and use this to define a RemapTable 1006 ColorMap colorMap = new ColorMap(); 1007 1008 //My watermark was defined with a background of 100% Green this will 1009 //be the color we search for and replace with transparency 1010 colorMap.OldColor = Color.FromArgb(255, 0, 255, 0); 1011 colorMap.NewColor = Color.FromArgb(0, 0, 0, 0); 1012 1013 ColorMap[] remapTable = {colorMap}; 1014 1015 imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap); 1016 1017 //The second color manipulation is used to change the opacity of the 1018 //watermark. This is done by applying a 5x5 matrix that contains the 1019 //coordinates for the RGBA space. By setting the 3rd row and 3rd column 1020 //to 0.3f we achive a level of opacity 1021 float[][] colorMatrixElements = { 1022 new float[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f}, 1023 new float[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f}, 1024 new float[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f}, 1025 new float[] {0.0f, 0.0f, 0.0f, 0.3f, 0.0f}, 1026 new float[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}}; 1027 ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements); 1028 1029 imageAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, 1030 ColorAdjustType.Bitmap); 1031 1032 //For this example we will place the watermark in the upper right 1033 //hand corner of the photograph. offset down 10 pixels and to the 1034 //left 10 pixles 1035 1036 int xPosOfWm = ((phWidth - wmWidth)-10); 1037 int yPosOfWm = 10; 1038 1039 grWatermark.DrawImage(imgWatermark, 1040 new Rectangle(xPosOfWm,yPosOfWm,wmWidth,wmHeight), //Set the detination Position 1041 0, // x-coordinate of the portion of the source image to draw. 1042 0, // y-coordinate of the portion of the source image to draw. 1043 wmWidth, // Watermark Width 1044 wmHeight, // Watermark Height 1045 GraphicsUnit.Pixel, // Unit of measurment 1046 imageAttributes); //ImageAttributes Object 1047 1048 //Replace the original photgraphs bitmap with the new Bitmap 1049 imgPhoto = bmWatermark; 1050 grPhoto.Dispose(); 1051 grWatermark.Dispose(); 1052 1053 //save new image to file system. 1054 imgPhoto.Save(WorkingDirectory + ImageName +"_finally.jpg", ImageFormat.Jpeg); 1055 imgPhoto.Dispose(); 1056 imgWatermark.Dispose(); 1057 1058 1059 } 1060 } 1061 1062 1063 //水印图片加水印文字 1064 // ReDrawImg img = new ReDrawImg(); 1065 // img .PublicWorkingDirectory = @"C:\Watermark_src\WaterPic\"; 1066 // img .PublicImageName = "watermark_photo.jpg"; 1067 // img .PublicImageWater = "watermark.bmp"; 1068 // img .PublicFontString = "清清月儿"; 1069 // img .DealImage(); 1070 1071 //水印文字 1072 ReDrawImg img = new ReDrawImg(); 1073 img .PublicWorkingDirectory = @"C:\Watermark_src\WaterPic\"; 1074 img .PublicImageName = "watermark_photo.jpg"; 1075 img .PublicFontString = @"清清月儿"; 1076 img .DealImage(); 1077 1078 1079 //水印图片 1080 // ReDrawImg img = new ReDrawImg(); 1081 // img .PublicWorkingDirectory = @"C:\Watermark_src\WaterPic\"; 1082 // img .PublicImageName = "watermark_photo.jpg"; 1083 // img .PublicImageWater = "watermark.bmp"; 1084 // img .DealImage(); 1085 1086 1087 后台代码: 1088 1089 using System; 1090 using System.Data; 1091 using System.Configuration; 1092 using System.Collections; 1093 using System.Web; 1094 using System.Web.Security; 1095 using System.Web.UI; 1096 using System.Web.UI.WebControls; 1097 using System.Web.UI.WebControls.WebParts; 1098 using System.Web.UI.HtmlControls; 1099 public partial class _Default : System.Web.UI.Page 1100 { 1101 1102 protected void Page_Load(object sender, EventArgs e) 1103 { 1104 1105 } 1106 protected void bt_upload_Click(object sender, EventArgs e) 1107 { 1108 try 1109 { 1110 if (FileUpload1.PostedFile.FileName == "") 1111 { 1112 this.lb_info.Text = "请选择文件!"; 1113 } 1114 else 1115 { 1116 string filepath = FileUpload1.PostedFile.FileName; 1117 string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1); 1118 string serverpath1 = Server.MapPath("images/") + filename; 1119 //string serverpath2 = Server.MapPath("images/") + System.DateTime.Now.ToString("yyy-MM-dd-hh-mm-ss") + Session.SessionID + filename; 1120 FileUpload1.PostedFile.SaveAs(serverpath1); 1121 //ImageThumbnail img = new ImageThumbnail(filepath); 1122 //img.ReducedImage(0.4, serverpath2); 1123 DrawImg img = new DrawImg(); 1124 img.PublicWorkingDirectory = Server.MapPath("images/"); 1125 img.PublicImageName = filename; 1126 img.PublicFontString = "http://blog.csdn.Net/21as.Net"; 1127 img.PublicImageWater = "yyy.jpg"; 1128 img.DealImage(); 1129 this.lb_info.Text = "上传成功!"; 1130 } 1131 } 1132 catch (Exception error) 1133 { 1134 this.lb_info.Text = "上传发生错误!原因:" + error.ToString(); 1135 } 1136 } 1137 } 1138 1139 1140 1141 1142 1143 1144
嗯希望各位多多提意见,先在这里谢谢哈,也希望一切顺心!