C#图片加水印实例与代码
程序员文章站
2022-05-25 13:30:05
...
本文要提供的类可以为图片加文字水印,以及判断是否是图片文件。经过测试可运行,例子请下载:http://hovertree.com/h/bjaf/5qc5eh6y.htm 例子效果图: 以下是HovercWarter类的代码: 1 using System.Drawing; 2 using System.Drawing.Imaging; 3 using Syst
本文要提供的类可以为图片加文字水印,以及判断是否是图片文件。经过测试可运行,例子请下载: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 ///46 /// 根据文件头判断上传的文件类型 47 /// 48 /// filePath是文件的完整路径 49 /// 返回true或false 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