zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C#添加图片水印类实现代码

c#代码 实现 图片 添加 水印
2023-06-13 09:14:09 时间
复制代码代码如下:

usingSystem;
usingSystem.Collections.Generic;
usingSystem.Text;
usingSystem.Drawing;
usingSystem.IO;
usingSystem.Drawing.Imaging;
usingSystem.Web;
usingSystem.Drawing.Drawing2D;
usingSystem.Reflection;
namespaceChen
{
publicclasswarterPic
{
///<summary>
///给图片上水印
///</summary>
///<paramname="filepath">原图片地址</param>
///<paramname="waterfile">水印图片地址</param>
///
publicvoidmarkwater(stringfilepath,stringwaterfile)
{
//gif不水印
inti=filepath.LastIndexOf(".");
stringex=filepath.Substring(i,filepath.Length-i);
if(string.Compare(ex,".gif",true)==0)
{
return;
}
stringmodifyimagepath=filepath;//修改的图像路径
intlucencypercent=25;
Imagemodifyimage=null;
Imagedrawedimage=null;
Graphicsg=null;
try
{
//建立图形对象
modifyimage=Image.FromFile(modifyimagepath,true);
drawedimage=Image.FromFile(waterfile,true);
g=Graphics.FromImage(modifyimage);
//获取要绘制图形坐标
intx=modifyimage.Width-drawedimage.Width;
inty=modifyimage.Height-drawedimage.Height;//设置颜色矩阵
float[][]matrixitems={newfloat[]{1,0,0,0,0},newfloat[]{0,1,0,0,0},newfloat[]{0,0,1,0,0},newfloat[]{0,0,0,(float)lucencypercent/100f,0},newfloat[]{0,0,0,0,1}};
ColorMatrixcolormatrix=newColorMatrix(matrixitems);
ImageAttributesimgattr=newImageAttributes();
imgattr.SetColorMatrix(colormatrix,ColorMatrixFlag.Default,ColorAdjustType.Bitmap);//绘制阴影图像
g.DrawImage(drawedimage,newRectangle(x,y,drawedimage.Width,drawedimage.Height),10,10,drawedimage.Width,drawedimage.Height,GraphicsUnit.Pixel,imgattr);//保存文件
string[]allowimagetype={".jpg",".gif",".png",".bmp",".tiff",".wmf",".ico"};
FileInfofi=newFileInfo(modifyimagepath);
ImageFormatimagetype=ImageFormat.Gif;
switch(fi.Extension.ToLower())
{
case".jpg":
imagetype=ImageFormat.Jpeg;
break;
case".gif":
imagetype=ImageFormat.Gif;
break;
case".png":
imagetype=ImageFormat.Png;
break;
case".bmp":
imagetype=ImageFormat.Bmp;
break;
case".tif":
imagetype=ImageFormat.Tiff;
break;
case".wmf":
imagetype=ImageFormat.Wmf;
break;
case".ico":
imagetype=ImageFormat.Icon;
break;
default:break;
}
MemoryStreamms=newMemoryStream();
modifyimage.Save(ms,imagetype);
byte[]imgdata=ms.ToArray();
modifyimage.Dispose();
drawedimage.Dispose();
g.Dispose();
FileStreamfs=null;
//File.Delete(modifyimagepath);
fs=newFileStream(modifyimagepath,FileMode.Create,FileAccess.Write);
if(fs!=null)
{
fs.Write(imgdata,0,imgdata.Length);
fs.Close();
}
}
finally
{
try
{
drawedimage.Dispose();
modifyimage.Dispose();
g.Dispose();
}
catch
{}
}
}
}
}