CSharp examples for System.Drawing:Image Operation
add Watermark Text
using System.Web; using System.Runtime.InteropServices; using System.Drawing.Imaging; using System.Drawing.Drawing2D; using System.Drawing; using System;//from w w w . j av a2 s . c o m public class Main{ public static bool addWatermarkText(string oldpath, string newpath, string _watermarkText, string _watermarkPosition = "WM_CENTER", string fontStyle = "arial", int fontSize = 14, string color = "#FFFFFF") { try { StringFormat format; Image image = Image.FromFile(HttpContext.Current.Server.MapPath(oldpath)); Bitmap bitmap = new Bitmap(image.Width, image.Height, PixelFormat.Format24bppRgb); Graphics graphics = Graphics.FromImage(bitmap); graphics.Clear(Color.White); graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.InterpolationMode = InterpolationMode.High; graphics.DrawImage(image, 0, 0, image.Width, image.Height); Font font = null; SizeF ef = new SizeF(); font = new Font(fontStyle, (float) fontSize); ef = graphics.MeasureString(_watermarkText, font); float x = 0f; float y = 0f; string str = _watermarkPosition; if (str != null) { if (!(str == "WM_TOP_LEFT")) { if (str == "WM_TOP_RIGHT") { goto Label_0104; } if (str == "WM_BOTTOM_RIGHT") { goto Label_012D; } if (str == "WM_BOTTOM_LEFT") { goto Label_0163; } if (str == "WM_CENTER") { goto Label_018B; } } else { x = ef.Width / 2f; y = 8f; } } goto Label_01B7; Label_0104: x = (image.Width * 1f) - (ef.Width / 2f); y = 8f; goto Label_01B7; Label_012D: x = (image.Width * 1f) - (ef.Width / 2f); y = (image.Height * 1f) - ef.Height; goto Label_01B7; Label_0163: x = ef.Width / 2f; y = (image.Height * 1f) - ef.Height; goto Label_01B7; Label_018B: x = image.Width * 0.5f; y = (image.Height * 0.5f) - (ef.Height / 2f); Label_01B7: format = new StringFormat(); format.Alignment = StringAlignment.Center; SolidBrush brush = new SolidBrush(Color.FromArgb(0x99, 0, 0, 0)); graphics.DrawString(_watermarkText, font, brush, x + 1f, y + 1f, format); SolidBrush brush2 = new SolidBrush(Color.FromArgb(0x99, ColorTranslator.FromHtml(color))); graphics.DrawString(_watermarkText, font, brush2, x, y, format); brush.Dispose(); brush2.Dispose(); bitmap.Save(HttpContext.Current.Server.MapPath(newpath)); bitmap.Dispose(); image.Dispose(); return true; } catch { } return false; } }