本文要提供的類可以為圖片加文字水印,以及判斷是否是圖片文件。經過測試可運行,例子請下載:http://hovertree.com/h/bjaf/5qc5eh6y.htm
例子效果圖:
以下是HovercWarter類的代碼:
1 using System.Drawing; 2 using System.Drawing.Imaging; 3 using System.IO; 4 5 namespace HoverTreeBatch.HovercFrame 6 { 7 public class HovercWarter 8 { 9 public static Image AddTextToImg(Image image, string text) 10 { 11 Bitmap bitmap = new Bitmap(image, image.Width, image.Height); 12 Graphics g = Graphics.FromImage(bitmap); 13 14 float fontSize = 12.0f; //字體大小 15 float textWidth = text.Length * fontSize; //文本的長度 16 //下面定義一個矩形區域,以後在這個矩形裡畫上白底黑字 17 float rectX = 0; 18 float rectY = 0; 19 float rectWidth = text.Length * (fontSize + 8); 20 float rectHeight = fontSize + 8; 21 //聲明矩形域 22 RectangleF textArea = new RectangleF(rectX, rectY, rectWidth, rectHeight); 23 24 Font font = new Font("宋體", fontSize); //定義字體 25 Brush whiteBrush = new SolidBrush(Color.White); //白筆刷,畫文字用 26 Brush blackBrush = new SolidBrush(Color.Black); //黑筆刷,畫背景用 27 28 g.FillRectangle(blackBrush, rectX, rectY, rectWidth, rectHeight); 29 30 g.DrawString(text, font, whiteBrush, textArea); 31 MemoryStream ms = new MemoryStream(); 32 //保存為Jpg類型 33 bitmap.Save(ms, ImageFormat.Jpeg); 34 35 Image h_hovercImg = Image.FromStream(ms); 36 37 g.Dispose(); 38 bitmap.Dispose(); 39 40 41 return h_hovercImg; 42 } 43 44 45 /// <summary> 46 /// 根據文件頭判斷上傳的文件類型 47 /// </summary> 48 /// <param name="filePath">filePath是文件的完整路徑 </param> 49 /// <returns>返回true或false</returns> 50 public static bool IsPicture(string filePath) 51 { 52 try 53 { 54 FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read); 55 BinaryReader reader = new BinaryReader(fs); 56 string fileClass; 57 byte buffer; 58 buffer = reader.ReadByte(); 59 fileClass = buffer.ToString(); 60 buffer = reader.ReadByte(); 61 fileClass += buffer.ToString(); 62 reader.Close(); 63 fs.Close(); 64 if (fileClass == "255216" || fileClass == "7173" || fileClass == "13780" || fileClass == "6677") 65 //何問起 hovertree.com 66 //255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar 67 { 68 return true; 69 } 70 else 71 { 72 return false; 73 } 74 } 75 catch 76 { 77 return false; 78 } 79 } 80 } 81 }
另外出一道.NET的題目:http://hovertree.com/shortanswer/bjaf/9vqxwuda.htm
開發技術文章收集: http://www.cnblogs.com/sosoft/p/kaifajishu.html