如何生成log新信息背景图片和在图片上添加水印
在图片上添加文字水印,其实就是要用到两个类,
using System.Drawing;
using System.Drawing.Drawing2D;
废话不多说了,直接上代码;代码很容易看懂;
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Drawing; using System.Drawing.Drawing2D; namespace WebApplication10 { public enum Postion { LeftTop, RightTop, LeftButtom, RightButtom, Center } public class Watermark { public void AddTextToIMage(string IMagePath,string TextStr,Postion postion,string familyfont,float fontSize) { //设置文字水印的区域 float RectX = 0; float RectY = 0; float RectWidth = 0; float RectHeight = 0; //获取图片 System.Drawing.Image image = System.Drawing.Image.FromFile(IMagePath); System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(image); Graphics g = Graphics.FromImage(bitmap); if(fontSize>(float)(image.Height/10.0) || fontSize>(float)(image.Width/10.0)) { fontSize = (fontSize > (float)(image.Height / 10.0)) == true ? (float)(image.Height / 10.0) : (float)(image.Width / 10.0); } //设置字体 Font font = new Font(familyfont, fontSize); RectWidth = (fontSize + 2) * TextStr.Length; RectHeight = fontSize + 4; StringFormat strFormat = new StringFormat(); strFormat.Alignment = StringAlignment.Center; //设置画刷 Color color = Color.FromArgb(221, 221, 221); HatchBrush hbbrush = new HatchBrush(HatchStyle.DiagonalCross, color, color); switch(postion) { case Postion.LeftTop: RectX = 0; RectY = 0; break; case Postion.LeftButtom: RectX = 0; RectY = image.Height - RectHeight; break; case Postion.RightTop: RectX = image.Width - RectWidth; RectY = 0; break; case Postion.RightButtom: RectX = image.Width - RectWidth; RectY = image.Height - RectHeight; break; case Postion.Center: RectX = (image.Width - RectWidth) / 2; RectY = (image.Height - RectHeight) / 2; break; } RectangleF rectf = new RectangleF(RectX, RectY, RectWidth, RectHeight); g.DrawString(TextStr, font, hbbrush, rectf, strFormat); System.IO.MemoryStream ms = new System.IO.MemoryStream(); bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); System.Web.HttpContext.Current.Response.Clear(); System.Web.HttpContext.Current.Response.ContentType = "image/jpeg"; System.Web.HttpContext.Current.Response.BinaryWrite(ms.ToArray()); g.Dispose(); bitmap.Dispose(); image.Dispose(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication10 { public partial class _default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Watermark watermark = new Watermark(); watermark.AddTextToIMage(Server.MapPath("/Images/sss.JPG"), "你好2016!", Postion.Center, "宋体", 15.0f); } } }
结果演示图:
歡迎分享,謝謝!