C#圖片添加水印的實(shí)現(xiàn)代碼
本文實(shí)例介紹了C#圖片添加水印的實(shí)現(xiàn)方法,可以為圖片加文字水印,及判斷是否是圖片文件,分享給大家供大家參考,具體內(nèi)容如下
效果圖:

以下是HovercWarter類(lèi)的代碼:
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類(lèi)型
bitmap.Save(ms, ImageFormat.Jpeg);
Image h_hovercImg = Image.FromStream(ms);
g.Dispose();
bitmap.Dispose();
return h_hovercImg;
}
/// <summary>
/// 根據(jù)文件頭判斷上傳的文件類(lèi)型
/// </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# Winform 分頁(yè)功能的實(shí)現(xiàn)
本文主要介紹了C# Winform 分頁(yè)功能的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06
C#實(shí)現(xiàn)在購(gòu)物車(chē)系統(tǒng)中生成不重復(fù)訂單號(hào)的方法
這篇文章主要介紹了C#實(shí)現(xiàn)在購(gòu)物車(chē)系統(tǒng)中生成不重復(fù)訂單號(hào)的方法,涉及C#中時(shí)間與字符串操作的相關(guān)技巧,非常簡(jiǎn)單實(shí)用,需要的朋友可以參考下2015-05-05
C# 當(dāng)前系統(tǒng)時(shí)間獲取及時(shí)間格式詳解
這篇文章主要介紹了C# 當(dāng)前系統(tǒng)時(shí)間獲取及時(shí)間格式詳解的相關(guān)資料,這里提供代碼實(shí)例,幫助大家學(xué)習(xí)參考,需要的朋友可以參考下2016-12-12
WinForm實(shí)現(xiàn)按名稱(chēng)遞歸查找控件的方法
這篇文章主要介紹了WinForm實(shí)現(xiàn)按名稱(chēng)遞歸查找控件的方法,需要的朋友可以參考下2014-08-08

