C#实现给图片加水印的方法
本文实例讲述了C#实现给图片加水印的方法。分享给大家供大家参考,具体如下:
usingSystem;
usingSystem.Drawing;
usingSystem.Drawing.Imaging;
usingSystem.Drawing.Drawing2D;
namespaceTutorial
{
classWaterMark
{
[STAThread]
staticvoidMain(string[]args)
{
//setaworkingdirectory
stringWorkingDirectory=@"C:\DocumentsandSettings\administrator.JAZZMINE\MyDocuments\Projects\Tutorials\WaterMark";
//defineastringoftexttouseastheCopyrightmessage
stringCopyright="Copyright?2002-APPhoto/DavidZalubowski";
//createaimageobjectcontainingthephotographtowatermark
ImageimgPhoto=Image.FromFile(WorkingDirectory+"\\watermark_photo.jpg");
intphWidth=imgPhoto.Width;
intphHeight=imgPhoto.Height;
//createaBitmaptheSizeoftheoriginalphotograph
BitmapbmPhoto=newBitmap(phWidth,phHeight,PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(imgPhoto.HorizontalResolution,imgPhoto.VerticalResolution);
//loadtheBitmapintoaGraphicsobject
GraphicsgrPhoto=Graphics.FromImage(bmPhoto);
//createaimageobjectcontainingthewatermark
ImageimgWatermark=newBitmap(WorkingDirectory+"\\watermark.bmp");
intwmWidth=imgWatermark.Width;
intwmHeight=imgWatermark.Height;
//------------------------------------------------------------
//Step#1-InsertCopyrightmessage
//------------------------------------------------------------
//SettherenderingqualityforthisGraphicsobject
grPhoto.SmoothingMode=SmoothingMode.AntiAlias;
//DrawsthephotoImageobjectatoriginalsizetothegraphicsobject.
grPhoto.DrawImage(
imgPhoto,//PhotoImageobject
newRectangle(0,0,phWidth,phHeight),//Rectanglestructure
0,//x-coordinateoftheportionofthesourceimagetodraw.
0,//y-coordinateoftheportionofthesourceimagetodraw.
phWidth,//Widthoftheportionofthesourceimagetodraw.
phHeight,//Heightoftheportionofthesourceimagetodraw.
GraphicsUnit.Pixel);//Unitsofmeasure
//-------------------------------------------------------
//tomaximizethesizeoftheCopyrightmessagewewill
//testmultipleFontsizestodeterminethelargestposible
//fontwecanuseforthewidthofthePhotograph
//defineanarrayofpointsizesyouwouldliketoconsideraspossiblities
//-------------------------------------------------------
int[]sizes=newint[]{16,14,12,10,8,6,4};
FontcrFont=null;
SizeFcrSize=newSizeF();
//LoopthroughthedefinedsizescheckingthelengthoftheCopyrightstring
//IfitslengthinpixlesislessthentheimagewidthchoosethisFontsize.
for(inti=0;i<7;i++)
{
//setaFontobjecttoArial(i)pt,Bold
crFont=newFont("arial",sizes[i],FontStyle.Bold);
//MeasuretheCopyrightstringinthisFont
crSize=grPhoto.MeasureString(Copyright,crFont);
if((ushort)crSize.Width<(ushort)phWidth)
break;
}
//Sinceallphotographswillhavevaryingheights,determinea
//position5%fromthebottomoftheimage
intyPixlesFromBottom=(int)(phHeight*.05);
//NowthatwehaveapointsizeusetheCopyrightsstringheight
//todetermineay-coordinatetodrawthestringofthephotograph
floatyPosFromBottom=((phHeight-yPixlesFromBottom)-(crSize.Height/2));
//Determineitsx-coordinatebycalculatingthecenterofthewidthoftheimage
floatxCenterOfImg=(phWidth/2);
//Definethetextlayoutbysettingthetextalignmenttocentered
StringFormatStrFormat=newStringFormat();
StrFormat.Alignment=StringAlignment.Center;
//defineaBrushwhichissemitrasparentblack(Alphasetto153)
SolidBrushsemiTransBrush2=newSolidBrush(Color.FromArgb(153,0,0,0));
//DrawtheCopyrightstring
grPhoto.DrawString(Copyright,//stringoftext
crFont,//font
semiTransBrush2,//Brush
newPointF(xCenterOfImg+1,yPosFromBottom+1),//Position
StrFormat);
//defineaBrushwhichissemitrasparentwhite(Alphasetto153)
SolidBrushsemiTransBrush=newSolidBrush(Color.FromArgb(153,255,255,255));
//DrawtheCopyrightstringasecondtimetocreateashadoweffect
//Makesuretomovethistext1pixeltotherightanddown1pixel
grPhoto.DrawString(Copyright,//stringoftext
crFont,//font
semiTransBrush,//Brush
newPointF(xCenterOfImg,yPosFromBottom),//Position
StrFormat);//Textalignment
//------------------------------------------------------------
//Step#2-InsertWatermarkimage
//------------------------------------------------------------
//CreateaBitmapbasedonthepreviouslymodifiedphotographBitmap
BitmapbmWatermark=newBitmap(bmPhoto);
bmWatermark.SetResolution(imgPhoto.HorizontalResolution,imgPhoto.VerticalResolution);
//LoadthisBitmapintoanewGraphicObject
GraphicsgrWatermark=Graphics.FromImage(bmWatermark);
//Toachieveatransulcentwatermarkwewillapply(2)color
//manipulationsbydefineingaImageAttributesobjectand
//seting(2)ofitsproperties.
ImageAttributesimageAttributes=newImageAttributes();
//Thefirststepinmanipulatingthewatermarkimageistoreplace
//thebackgroundcolorwithonethatistrasparent(Alpha=0,R=0,G=0,B=0)
//todothiswewilluseaColormapandusethistodefineaRemapTable
ColorMapcolorMap=newColorMap();
//Mywatermarkwasdefinedwithabackgroundof100%Greenthiswill
//bethecolorwesearchforandreplacewithtransparency
colorMap.OldColor=Color.FromArgb(255,0,255,0);
colorMap.NewColor=Color.FromArgb(0,0,0,0);
ColorMap[]remapTable={colorMap};
imageAttributes.SetRemapTable(remapTable,ColorAdjustType.Bitmap);
//Thesecondcolormanipulationisusedtochangetheopacityofthe
//watermark.Thisisdonebyapplyinga5x5matrixthatcontainsthe
//coordinatesfortheRGBAspace.Bysettingthe3rdrowand3rdcolumn
//to0.3fweachivealevelofopacity
float[][]colorMatrixElements={
newfloat[]{1.0f,0.0f,0.0f,0.0f,0.0f},
newfloat[]{0.0f,1.0f,0.0f,0.0f,0.0f},
newfloat[]{0.0f,0.0f,1.0f,0.0f,0.0f},
newfloat[]{0.0f,0.0f,0.0f,0.3f,0.0f},
newfloat[]{0.0f,0.0f,0.0f,0.0f,1.0f}};
ColorMatrixwmColorMatrix=newColorMatrix(colorMatrixElements);
imageAttributes.SetColorMatrix(wmColorMatrix,ColorMatrixFlag.Default,
ColorAdjustType.Bitmap);
//Forthisexamplewewillplacethewatermarkintheupperright
//handcornerofthephotograph.offsetdown10pixelsandtothe
//left10pixles
intxPosOfWm=((phWidth-wmWidth)-10);
intyPosOfWm=10;
grWatermark.DrawImage(imgWatermark,
newRectangle(xPosOfWm,yPosOfWm,wmWidth,wmHeight),//SetthedetinationPosition
0,//x-coordinateoftheportionofthesourceimagetodraw.
0,//y-coordinateoftheportionofthesourceimagetodraw.
wmWidth,//WatermarkWidth
wmHeight,//WatermarkHeight
GraphicsUnit.Pixel,//Unitofmeasurment
imageAttributes);//ImageAttributesObject
//ReplacetheoriginalphotgraphsbitmapwiththenewBitmap
imgPhoto=bmWatermark;
grPhoto.Dispose();
grWatermark.Dispose();
//savenewimagetofilesystem.
imgPhoto.Save(WorkingDirectory+"\\watermark_final.jpg",ImageFormat.Jpeg);
imgPhoto.Dispose();
imgWatermark.Dispose();
}
}
}
更多关于C#相关内容感兴趣的读者可查看本站专题:《C#图片操作技巧汇总》、《C#字符串操作技巧总结》及《C#面向对象程序设计入门教程》
希望本文所述对大家C#程序设计有所帮助。