当前位置: 代码迷 >> C# >> C#图片加水印范例与代码
  详细解决方案

C#图片加水印范例与代码

热度:318   发布时间:2016-04-28 08:24:13.0
C#图片加水印实例与代码

本文要提供的类可以为图片加文字水印,以及判断是否是图片文件。经过测试可运行,例子请下载: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 try53 {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.com66 //255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar 67 {68 return true;69 }70 else71 {72 return false;73 }74 }75 catch76 {77 return false;78 }79 }80 }81 }

另外出一道.NET的题目:http://hovertree.com/shortanswer/bjaf/9vqxwuda.htm

开发技术文章收集: http://www.cnblogs.com/sosoft/p/kaifajishu.html

  相关解决方案