C#(.net)水印图片的生成完整实例
本文以一个完整实例讲述了C#水印图片的生成方法。是非常实用的技巧。分享给大家供大家参考。
具体实例代码如下:
/*
*
*使用说明:
*建议先定义一个WaterImage实例
*然后利用实例的属性,去匹配需要进行操作的参数
*然后定义一个WaterImageManage实例
*利用WaterImageManage实例进行DrawImage(),印图片水印
*DrawWords()印文字水印
*
*/
usingSystem;
usingSystem.Drawing;
usingSystem.Drawing.Imaging;
usingSystem.Drawing.Drawing2D;
usingSystem.IO;
namespaceABC
{
///<summary>
///图片位置
///</summary>
publicenumImagePosition
{
LeftTop,//左上
LeftBottom,//左下
RightTop,//右上
RigthBottom,//右下
TopMiddle,//顶部居中
BottomMiddle,//底部居中
Center//中心
}
///<summary>
///水印图片的操作管理DesignbyGaryGongFromDemetersoft.com
///</summary>
publicclassWaterImageManage
{
///<summary>
///生成一个新的水印图片制作实例
///</summary>
publicWaterImageManage()
{
//
//TODO:Addconstructorlogichere
//
}
///<summary>
///添加图片水印
///</summary>
///<paramname="sourcePicture">源图片文件名</param>
///<paramname="waterImage">水印图片文件名</param>
///<paramname="alpha">透明度(0.1-1.0数值越小透明度越高)</param>
///<paramname="position">位置</param>
///<paramname="PicturePath">图片的路径</param>
///<returns>返回生成于指定文件夹下的水印文件名</returns>
publicstringDrawImage(stringsourcePicture,
stringwaterImage,
floatalpha,
ImagePositionposition,
stringPicturePath)
{
//
//判断参数是否有效
//
if(sourcePicture==string.Empty||waterImage==string.Empty||alpha==0.0||PicturePath==string.Empty)
{
returnsourcePicture;
}
//
//源图片,水印图片全路径
//
stringsourcePictureName=PicturePath+sourcePicture;
stringwaterPictureName=PicturePath+waterImage;
stringfileSourceExtension=System.IO.Path.GetExtension(sourcePictureName).ToLower();
stringfileWaterExtension=System.IO.Path.GetExtension(waterPictureName).ToLower();
//
//判断文件是否存在,以及类型是否正确
//
if(System.IO.File.Exists(sourcePictureName)==false||
System.IO.File.Exists(waterPictureName)==false||(
fileSourceExtension!=".gif"&&
fileSourceExtension!=".jpg"&&
fileSourceExtension!=".png")||(
fileWaterExtension!=".gif"&&
fileWaterExtension!=".jpg"&&
fileWaterExtension!=".png")
)
{
returnsourcePicture;
}
//
//目标图片名称及全路径
//
stringtargetImage=sourcePictureName.Replace(System.IO.Path.GetExtension(sourcePictureName),"")+"_1101.jpg";
//
//将需要加上水印的图片装载到Image对象中
//
ImageimgPhoto=Image.FromFile(sourcePictureName);
//
//确定其长宽
//
intphWidth=imgPhoto.Width;
intphHeight=imgPhoto.Height;
//
//封装GDI+位图,此位图由图形图像及其属性的像素数据组成。
//
BitmapbmPhoto=newBitmap(phWidth,phHeight,PixelFormat.Format24bppRgb);
//
//设定分辨率
//
bmPhoto.SetResolution(imgPhoto.HorizontalResolution,imgPhoto.VerticalResolution);
//
//定义一个绘图画面用来装载位图
//
GraphicsgrPhoto=Graphics.FromImage(bmPhoto);
//
//同样,由于水印是图片,我们也需要定义一个Image来装载它
//
ImageimgWatermark=newBitmap(waterPictureName);
//
//获取水印图片的高度和宽度
//
intwmWidth=imgWatermark.Width;
intwmHeight=imgWatermark.Height;
//SmoothingMode:指定是否将平滑处理(消除锯齿)应用于直线、曲线和已填充区域的边缘。
//成员名称说明
//AntiAlias指定消除锯齿的呈现。
//Default指定不消除锯齿。
//HighQuality指定高质量、低速度呈现。
//HighSpeed指定高速度、低质量呈现。
//Invalid指定一个无效模式。
//None指定不消除锯齿。
grPhoto.SmoothingMode=SmoothingMode.AntiAlias;
//
//第一次描绘,将我们的底图描绘在绘图画面上
//
grPhoto.DrawImage(imgPhoto,
newRectangle(0,0,phWidth,phHeight),
0,
0,
phWidth,
phHeight,
GraphicsUnit.Pixel);
//
//与底图一样,我们需要一个位图来装载水印图片。并设定其分辨率
//
BitmapbmWatermark=newBitmap(bmPhoto);
bmWatermark.SetResolution(imgPhoto.HorizontalResolution,imgPhoto.VerticalResolution);
//
//继续,将水印图片装载到一个绘图画面grWatermark
//
GraphicsgrWatermark=Graphics.FromImage(bmWatermark);
//
//ImageAttributes对象包含有关在呈现时如何操作位图和图元文件颜色的信息。
//
ImageAttributesimageAttributes=newImageAttributes();
//
//Colormap:定义转换颜色的映射
//
ColorMapcolorMap=newColorMap();
//
//我的水印图被定义成拥有绿色背景色的图片被替换成透明
//
colorMap.OldColor=Color.FromArgb(255,0,255,0);
colorMap.NewColor=Color.FromArgb(0,0,0,0);
ColorMap[]remapTable={colorMap};
imageAttributes.SetRemapTable(remapTable,ColorAdjustType.Bitmap);
float[][]colorMatrixElements={
newfloat[]{1.0f,0.0f,0.0f,0.0f,0.0f},//red红色
newfloat[]{0.0f,1.0f,0.0f,0.0f,0.0f},//green绿色
newfloat[]{0.0f,0.0f,1.0f,0.0f,0.0f},//blue蓝色
newfloat[]{0.0f,0.0f,0.0f,alpha,0.0f},//透明度
newfloat[]{0.0f,0.0f,0.0f,0.0f,1.0f}};//
//ColorMatrix:定义包含RGBA空间坐标的5x5矩阵。
//ImageAttributes类的若干方法通过使用颜色矩阵调整图像颜色。
ColorMatrixwmColorMatrix=newColorMatrix(colorMatrixElements);
imageAttributes.SetColorMatrix(wmColorMatrix,ColorMatrixFlag.Default,
ColorAdjustType.Bitmap);
//
//上面设置完颜色,下面开始设置位置
//
intxPosOfWm;
intyPosOfWm;
switch(position)
{
caseImagePosition.BottomMiddle:
xPosOfWm=(phWidth-wmWidth)/2;
yPosOfWm=phHeight-wmHeight-10;
break;
caseImagePosition.Center:
xPosOfWm=(phWidth-wmWidth)/2;
yPosOfWm=(phHeight-wmHeight)/2;
break;
caseImagePosition.LeftBottom:
xPosOfWm=10;
yPosOfWm=phHeight-wmHeight-10;
break;
caseImagePosition.LeftTop:
xPosOfWm=10;
yPosOfWm=10;
break;
caseImagePosition.RightTop:
xPosOfWm=phWidth-wmWidth-10;
yPosOfWm=10;
break;
caseImagePosition.RigthBottom:
xPosOfWm=phWidth-wmWidth-10;
yPosOfWm=phHeight-wmHeight-10;
break;
caseImagePosition.TopMiddle:
xPosOfWm=(phWidth-wmWidth)/2;
yPosOfWm=10;
break;
default:
xPosOfWm=10;
yPosOfWm=phHeight-wmHeight-10;
break;
}
//第二次绘图,把水印印上去
//
grWatermark.DrawImage(imgWatermark,
newRectangle(xPosOfWm,
yPosOfWm,
wmWidth,
wmHeight),
0,
0,
wmWidth,
wmHeight,
GraphicsUnit.Pixel,
imageAttributes);
imgPhoto=bmWatermark;
grPhoto.Dispose();
grWatermark.Dispose();
//
//保存文件到服务器的文件夹里面
//
imgPhoto.Save(targetImage,ImageFormat.Jpeg);
imgPhoto.Dispose();
imgWatermark.Dispose();
returntargetImage.Replace(PicturePath,"");
}
/*
*
*使用说明:
*建议先定义一个WaterImage实例
*然后利用实例的属性,去匹配需要进行操作的参数
*然后定义一个WaterImageManage实例
*利用WaterImageManage实例进行DrawImage(),印图片水印
*DrawWords()印文字水印
*
-*/
///<summary>
///在图片上添加水印文字
///</summary>
///<paramname="sourcePicture">源图片文件(文件名,不包括路径)</param>
///<paramname="waterWords">需要添加到图片上的文字</param>
///<paramname="alpha">透明度</param>
///<paramname="position">位置</param>
///<paramname="PicturePath">文件路径</param>
///<returns></returns>
publicstringDrawWords(stringsourcePicture,
stringwaterWords,
floatalpha,
ImagePositionposition,
stringPicturePath)
{
//
//判断参数是否有效
//
if(sourcePicture==string.Empty||waterWords==string.Empty||alpha==0.0||PicturePath==string.Empty)
{
returnsourcePicture;
}
//
//源图片全路径
//
if(PicturePath.Substring(PicturePath.Length-1,1)!="/")
PicturePath+="/";
stringsourcePictureName=PicturePath+sourcePicture;
stringfileExtension=System.IO.Path.GetExtension(sourcePictureName).ToLower();
//
//判断文件是否存在,以及文件名是否正确
//
if(System.IO.File.Exists(sourcePictureName)==false||(
fileExtension!=".gif"&&
fileExtension!=".jpg"&&
fileExtension!=".png"))
{
returnsourcePicture;
}
//
//目标图片名称及全路径
//
stringtargetImage=sourcePictureName.Replace(System.IO.Path.GetExtension(sourcePictureName),"")+"_0703.jpg";
//创建一个图片对象用来装载要被添加水印的图片
ImageimgPhoto=Image.FromFile(sourcePictureName);
//获取图片的宽和高
intphWidth=imgPhoto.Width;
intphHeight=imgPhoto.Height;
//
//建立一个bitmap,和我们需要加水印的图片一样大小
BitmapbmPhoto=newBitmap(phWidth,phHeight,PixelFormat.Format24bppRgb);
//SetResolution:设置此Bitmap的分辨率
//这里直接将我们需要添加水印的图片的分辨率赋给了bitmap
bmPhoto.SetResolution(imgPhoto.HorizontalResolution,imgPhoto.VerticalResolution);
//Graphics:封装一个GDI+绘图图面。
GraphicsgrPhoto=Graphics.FromImage(bmPhoto);
//设置图形的品质
grPhoto.SmoothingMode=SmoothingMode.AntiAlias;
//将我们要添加水印的图片按照原始大小描绘(复制)到图形中
grPhoto.DrawImage(
imgPhoto,//要添加水印的图片
newRectangle(0,0,phWidth,phHeight),//根据要添加的水印图片的宽和高
0,//X方向从0点开始描绘
0,//Y方向
phWidth,//X方向描绘长度
phHeight,//Y方向描绘长度
GraphicsUnit.Pixel);//描绘的单位,这里用的是像素
//根据图片的大小我们来确定添加上去的文字的大小
//在这里我们定义一个数组来确定
int[]sizes=newint[]{16,14,12,10,8,6,4};
//字体
FontcrFont=null;
//矩形的宽度和高度,SizeF有三个属性,分别为Height高,width宽,IsEmpty是否为空
SizeFcrSize=newSizeF();
//利用一个循环语句来选择我们要添加文字的型号
//直到它的长度比图片的宽度小
for(inti=0;i<7;i++)
{
crFont=newFont("arial",sizes[i],FontStyle.Bold);
//测量用指定的Font对象绘制并用指定的StringFormat对象格式化的指定字符串。
crSize=grPhoto.MeasureString(waterWords,crFont);
//ushort关键字表示一种整数数据类型
if((ushort)crSize.Width<(ushort)phWidth)
break;
}
//截边5%的距离,定义文字显示(由于不同的图片显示的高和宽不同,所以按百分比截取)
intyPixlesFromBottom=(int)(phHeight*.05);
//定义在图片上文字的位置
floatwmHeight=crSize.Height;
floatwmWidth=crSize.Width;
floatxPosOfWm;
floatyPosOfWm;
switch(position)
{
caseImagePosition.BottomMiddle:
xPosOfWm=phWidth/2;
yPosOfWm=phHeight-wmHeight-10;
break;
caseImagePosition.Center:
xPosOfWm=phWidth/2;
yPosOfWm=phHeight/2;
break;
caseImagePosition.LeftBottom:
xPosOfWm=wmWidth;
yPosOfWm=phHeight-wmHeight-10;
break;
caseImagePosition.LeftTop:
xPosOfWm=wmWidth/2;
yPosOfWm=wmHeight/2;
break;
caseImagePosition.RightTop:
xPosOfWm=phWidth-wmWidth-10;
yPosOfWm=wmHeight;
break;
caseImagePosition.RigthBottom:
xPosOfWm=phWidth-wmWidth-10;
yPosOfWm=phHeight-wmHeight-10;
break;
caseImagePosition.TopMiddle:
xPosOfWm=phWidth/2;
yPosOfWm=wmWidth;
break;
default:
xPosOfWm=wmWidth;
yPosOfWm=phHeight-wmHeight-10;
break;
}
//封装文本布局信息(如对齐、文字方向和Tab停靠位),显示操作(如省略号插入和国家标准(National)数字替换)和OpenType功能。
StringFormatStrFormat=newStringFormat();
//定义需要印的文字居中对齐
StrFormat.Alignment=StringAlignment.Center;
//SolidBrush:定义单色画笔。画笔用于填充图形形状,如矩形、椭圆、扇形、多边形和封闭路径。
//这个画笔为描绘阴影的画笔,呈灰色
intm_alpha=Convert.ToInt32(256*alpha);
SolidBrushsemiTransBrush2=newSolidBrush(Color.FromArgb(m_alpha,0,0,0));
//描绘文字信息,这个图层向右和向下偏移一个像素,表示阴影效果
//DrawString在指定矩形并且用指定的Brush和Font对象绘制指定的文本字符串。
grPhoto.DrawString(waterWords,//stringoftext
crFont,//font
semiTransBrush2,//Brush
newPointF(xPosOfWm+1,yPosOfWm+1),//Position
StrFormat);
//从四个ARGB分量(alpha、红色、绿色和蓝色)值创建Color结构,这里设置透明度为153
//这个画笔为描绘正式文字的笔刷,呈白色
SolidBrushsemiTransBrush=newSolidBrush(Color.FromArgb(153,255,255,255));
//第二次绘制这个图形,建立在第一次描绘的基础上
grPhoto.DrawString(waterWords,//stringoftext
crFont,//font
semiTransBrush,//Brush
newPointF(xPosOfWm,yPosOfWm),//Position
StrFormat);
//imgPhoto是我们建立的用来装载最终图形的Image对象
//bmPhoto是我们用来制作图形的容器,为Bitmap对象
imgPhoto=bmPhoto;
//释放资源,将定义的Graphics实例grPhoto释放,grPhoto功德圆满
grPhoto.Dispose();
//将grPhoto保存
imgPhoto.Save(targetImage,ImageFormat.Jpeg);
imgPhoto.Dispose();
returntargetImage.Replace(PicturePath,"");
}
}
///<summary>
///装载水印图片的相关信息
///</summary>
publicclassWaterImage
{
publicWaterImage()
{
}
privatestringm_sourcePicture;
///<summary>
///源图片地址名字(带后缀)
///</summary>
publicstringSourcePicture
{
get{returnm_sourcePicture;}
set{m_sourcePicture=value;}
}
privatestringm_waterImager;
///<summary>
///水印图片名字(带后缀)
///</summary>
publicstringWaterPicture
{
get{returnm_waterImager;}
set{m_waterImager=value;}
}
privatefloatm_alpha;
///<summary>
///水印图片文字的透明度
///</summary>
publicfloatAlpha
{
get{returnm_alpha;}
set{m_alpha=value;}
}
privateImagePositionm_postition;
///<summary>
///水印图片或文字在图片中的位置
///</summary>
publicImagePositionPosition
{
get{returnm_postition;}
set{m_postition=value;}
}
privatestringm_words;
///<summary>
///水印文字的内容
///</summary>
publicstringWords
{
get{returnm_words;}
set{m_words=value;}
}
}
}
相信本文所述对大家的C#程序设计有一定的借鉴参考作用。