C#圖片添加水印的實(shí)現(xiàn)代碼
本文實(shí)例介紹了C#圖片添加水印的實(shí)現(xiàn)方法,可以為圖片加文字水印,及判斷是否是圖片文件,分享給大家供大家參考,具體內(nèi)容如下
效果圖:
以下是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; //文本的長(zhǎng)度 //下面定義一個(gè)矩形區(qū)域,以后在這個(gè)矩形里畫(huà)上白底黑字 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); //白筆刷,畫(huà)文字用 Brush blackBrush = new SolidBrush(Color.Black); //黑筆刷,畫(huà)背景用 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> /// 根據(jù)文件頭判斷上傳的文件類型 /// </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") //何問(wèn)起 hovertree.com //255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar { return true; } else { return false; } } catch { return false; } } } }
以上就是C#實(shí)現(xiàn)圖片添加水印的關(guān)鍵性代碼,希望對(duì)大家學(xué)習(xí)C#程序設(shè)計(jì)有所幫助。
相關(guān)文章
C#使用HttpWebRequest與HttpWebResponse模擬用戶登錄
這篇文章主要為大家詳細(xì)介紹了C#使用HttpWebRequest與HttpWebResponse模擬用戶登錄,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-04-04C#12中的Collection expressions集合表達(dá)式語(yǔ)法糖詳解
C#12中引入了新的語(yǔ)法糖來(lái)創(chuàng)建常見(jiàn)的集合,并且可以使用..來(lái)解構(gòu)集合,將其內(nèi)聯(lián)到另一個(gè)集合中,下面就跟隨小編一起學(xué)習(xí)一下C#12中這些語(yǔ)法糖的使用吧2023-11-11C#利用Spire.Pdf包實(shí)現(xiàn)為PDF添加數(shù)字簽名
Spire.PDF for .NET 是一款專業(yè)的基于.NET平臺(tái)的PDF文檔控制組件。它能夠讓開(kāi)發(fā)人員在不使用Adobe Acrobat和其他外部控件的情況下,運(yùn)用.NET 應(yīng)用程序創(chuàng)建,閱讀,編寫(xiě)和操縱PDF 文檔。本文將利用其實(shí)現(xiàn)添加數(shù)字簽名,需要的可以參考一下2022-08-08C#使用NPOI實(shí)現(xiàn)Excel導(dǎo)入導(dǎo)出功能
這篇文章主要為大家詳細(xì)介紹了C#使用NPOI實(shí)現(xiàn)Excel導(dǎo)入導(dǎo)出功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-02-02