標籤:
/// <summary> /// 給圖片加浮水印(圖片置中) /// </summary> /// <param name="srcImgPath">原始圖片路徑</param> /// <param name="waterPath">浮水印圖片路徑</param> /// <param name="waterWidth">浮水印地區的寬度</param> /// <param name="waterHeight">浮水印地區的高度</param> /// <param name="waterString">浮水印字元</param> /// <param name="markPosition">浮水印的位置</param> public static void MakeWaterPic(string srcImgPath, string waterPath, int waterWidth, int waterHeight, string waterString, string markPosition = "圖片中間") { //1. 從原圖片建立 Image 對象 using (Image img = Image.FromFile(srcImgPath)) { //2.用指定的大小和格式初始化 Bitmap 類的新執行個體 using (Bitmap map = new Bitmap(img.Width, img.Height, PixelFormat.Format32bppArgb)) { //3.從指定的 Image 對象建立新 Graphics 對象 using (Graphics g = Graphics.FromImage(map)) { //4.在指定位置並且按指定大小繪製 原圖片 對象 g.DrawImage(img, new Rectangle(0, 0, img.Width, img.Height), new RectangleF(0, 0, img.Width, img.Height), GraphicsUnit.Pixel); //g.DrawImage(map2,new Rectangle(0, 0, map2.Width, map2.Height)); // 設定浮水印字型 int fHeight = img.Height / 5; if (fHeight > 16) fHeight = 16; Font drawFont = new Font("Arial", fHeight); // 設定浮水印文字位置 int disX = 0, disY = 0; if (markPosition == "圖片中間") { disX = (img.Width - waterWidth) / 2; disY = (img.Height - waterHeight) / 2; } StringFormat drawFormat = new StringFormat(); drawFormat.FormatFlags = StringFormatFlags.NoWrap; //文本置中顯示 drawFormat.Alignment = StringAlignment.Center; drawFormat.LineAlignment = StringAlignment.Center; SolidBrush drawBrush = new SolidBrush(Color.White); //填充矩形 g.FillRectangle(drawBrush, new Rectangle(disX, disY, waterWidth, waterHeight)); drawBrush.Color = Color.Black; g.DrawString(waterString, drawFont, drawBrush, new RectangleF(disX, disY, waterWidth, waterHeight), drawFormat); map.Save(waterPath, ImageFormat.Jpeg); } } } }
二維碼名片