C#图片添加水印的实现代码
本文实例介绍了C#图片添加水印的实现方法,可以为图片加文字水印,及判断是否是图片文件,分享给大家供大家参考,具体内容如下
效果图:
以下是HovercWarter类的代码:
using System.Drawing; using System.Drawing.Imaging; using System.IO; namespace HoverTreeBatch.HovercFrame { public class HovercWarter { public static Image AddTextToImg(Image image, string text) { Bitmap bitmap = new Bitmap(image, image.Width, image.Height); Graphics g = Graphics.FromImage(bitmap); float fontSize = 12.0f; //字体大小 float textWidth = text.Length * fontSize; //文本的长度 //下面定义一个矩形区域,以后在这个矩形里画上白底黑字 float rectX = 0; float rectY = 0; float rectWidth = text.Length * (fontSize + 8); float rectHeight = fontSize + 8; //声明矩形域 RectangleF textArea = new RectangleF(rectX, rectY, rectWidth, rectHeight); Font font = new Font("宋体", fontSize); //定义字体 Brush whiteBrush = new SolidBrush(Color.White); //白笔刷,画文字用 Brush blackBrush = new SolidBrush(Color.Black); //黑笔刷,画背景用 g.FillRectangle(blackBrush, rectX, rectY, rectWidth, rectHeight); g.DrawString(text, font, whiteBrush, textArea); MemoryStream ms = new MemoryStream(); //保存为Jpg类型 bitmap.Save(ms, ImageFormat.Jpeg); Image h_hovercImg = Image.FromStream(ms); g.Dispose(); bitmap.Dispose(); return h_hovercImg; } /// <summary> /// 根据文件头判断上传的文件类型 /// </summary> /// <param name="filePath">filePath是文件的完整路径 </param> /// <returns>返回true或false</returns> public static bool IsPicture(string filePath) { try { FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read); BinaryReader reader = new BinaryReader(fs); string fileClass; byte buffer; buffer = reader.ReadByte(); fileClass = buffer.ToString(); buffer = reader.ReadByte(); fileClass += buffer.ToString(); reader.Close(); fs.Close(); if (fileClass == "255216" || fileClass == "7173" || fileClass == "13780" || fileClass == "6677") //何问起 hovertree.com //255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar { return true; } else { return false; } } catch { return false; } } } }
以上就是C#实现图片添加水印的关键性代码,希望对大家学习C#程序设计有所帮助。
赞 (0)