C#向圖片添加水印的兩種不同場景與解決方法
場景一
也就是大家經(jīng)常用的,一般是圖片的4個角落,基于橫縱坐標(biāo)來添加。
效果如下:

添加水印方法
static void addWatermarkText(Graphics picture,int fontsize, string _watermarkText, string _watermarkPosition, int _width, int _height)
{
int[] sizes = new int[] {32, 14, 12, 10, 8, 6, 4 };
Font crFont = null;
SizeF crSize = new SizeF();
crFont = new Font("微軟雅黑", fontsize, FontStyle.Bold);
crSize = picture.MeasureString(_watermarkText, crFont);
float xpos = 0;
float ypos = 0;
Color color =Color.Firebrick;
switch (_watermarkPosition)
{
case "WM_TOP_LEFT":
xpos = ((float)_width * (float).01) + (crSize.Width / 2);
ypos = (float)_height * (float).01;
break;
case "WM_TOP_RIGHT":
xpos = ((float)_width * (float).99) - (crSize.Width / 2);
ypos = (float)_height * (float).01;
break;
case "WM_BOTTOM_RIGHT":
xpos = ((float)_width * (float).99) - (crSize.Width / 2);
ypos = ((float)_height * (float).99) - crSize.Height;
break;
case "WM_BOTTOM_LEFT":
xpos = ((float)_width * (float).01) + (crSize.Width / 2);
ypos = ((float)_height * (float).99) - crSize.Height;
break;
}
StringFormat StrFormat = new StringFormat();
StrFormat.Alignment = StringAlignment.Center;
SolidBrush semiTransBrush2 = new SolidBrush(Color.FromArgb(153, 0, 0, 0));//加陰影
picture.DrawString(_watermarkText, crFont, semiTransBrush2, xpos + 1, ypos + 1, StrFormat);
SolidBrush semiTransBrush = new SolidBrush(color); //添加水印
picture.DrawString(_watermarkText, crFont, semiTransBrush, xpos, ypos, StrFormat);
semiTransBrush2.Dispose();
semiTransBrush.Dispose();
}
場景二
在圖片內(nèi)基于固定位置,文字始終居中。剛開始我基于第一種場景來根據(jù)水印漢字的長度來計算坐標(biāo),后來發(fā)現(xiàn)方法始終不可靠?,F(xiàn)在是先在圖片固定區(qū)域(水印區(qū)域)畫一個矩形,然后再矩形內(nèi)添加水印漢字,并使用畫刷保持文字居中。
效果圖如下

添加水印的方法
static void addWatermarkText(Graphics picture,string type, int fontsize, string _watermarkText)
{
//1、先畫矩形
RectangleF drawRect;
Color color;
if (type == "Top")
{
drawRect = new RectangleF(73, 135, 450, 64);
color = Color.FromArgb(255, 255, 255);
}
else
{
drawRect = new RectangleF(194, 245, 250, 39);
color = Color.FromArgb(244, 226, 38);
}
//2、在基于矩形畫水印文字
Font crFont = null;
StringFormat StrFormat = new StringFormat();
StrFormat.Alignment = StringAlignment.Center;
crFont = new Font("微軟雅黑", fontsize, FontStyle.Bold);
SolidBrush semiTransBrush = new SolidBrush(color); //添加水印
picture.DrawString(_watermarkText, crFont, semiTransBrush, drawRect, StrFormat);
semiTransBrush.Dispose();
}
總結(jié)
和第一種方法比起來,第二種方法更直觀,更短小精悍,只需要在你需要添加水印的圖片上計算好固定坐標(biāo)然后先畫一個矩形,然后把水印漢字畫在矩形內(nèi),這樣不管水印漢字如何變化都可以在圖片固定位置居中。以上就是這篇文章的全部內(nèi)容,希望能對大家的學(xué)習(xí)或者工作帶來一定的幫助。
相關(guān)文章
C# Dynamic關(guān)鍵字之:dynamic為什么比反射快的詳解
本篇文章是對C#中dynamic為什么比反射快進行了詳細的分析介紹,需要的朋友參考下2013-05-05
C#使用CallContext緩存線程數(shù)據(jù)
這篇文章介紹了C#使用CallContext緩存線程數(shù)據(jù)的方法,文中通過示例代碼介紹的非常詳細。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-05-05

