欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-03-09 13:23:05
复制代码 代码如下:using system; using system.collections.generic; using system.text; using sys...
复制代码 代码如下:

using system;
using system.collections.generic;
using system.text;
using system.drawing;
using system.io;
using system.drawing.imaging;
using system.web;
using system.drawing.drawing2d;
using system.reflection;
namespace chen
{
public class warterpic
{
/// <summary>
/// 给图片上水印
/// </summary>
/// <param name="filepath">原图片地址</param>
/// <param name="waterfile">水印图片地址</param>
///
public void markwater(string filepath, string waterfile)
{
//gif不水印
int i = filepath.lastindexof(".");
string ex = filepath.substring(i, filepath.length - i);
if (string.compare(ex, ".gif", true) == 0)
{
return;
}
string modifyimagepath = filepath;//修改的图像路径
int lucencypercent = 25;
image modifyimage = null;
image drawedimage = null;
graphics g = null;
try
{
//建立图形对象
modifyimage = image.fromfile(modifyimagepath, true);
drawedimage = image.fromfile(waterfile, true);
g = graphics.fromimage(modifyimage);
//获取要绘制图形坐标
int x = modifyimage.width - drawedimage.width;
int y = modifyimage.height - drawedimage.height; //设置颜色矩阵
float[][] matrixitems ={ new float[] { 1, 0, 0, 0, 0 }, new float[] { 0, 1, 0, 0, 0 }, new float[] { 0, 0, 1, 0, 0 }, new float[] { 0, 0, 0, (float)lucencypercent / 100f, 0 }, new float[] { 0, 0, 0, 0, 1 } };
colormatrix colormatrix = new colormatrix(matrixitems);
imageattributes imgattr = new imageattributes();
imgattr.setcolormatrix(colormatrix, colormatrixflag.default, coloradjusttype.bitmap); //绘制阴影图像
g.drawimage(drawedimage, new rectangle(x, y, drawedimage.width, drawedimage.height), 10, 10, drawedimage.width, drawedimage.height, graphicsunit.pixel, imgattr); //保存文件
string[] allowimagetype ={ ".jpg", ".gif", ".png", ".bmp", ".tiff", ".wmf", ".ico" };
fileinfo fi = new fileinfo(modifyimagepath);
imageformat imagetype = 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;
}
memorystream ms = new memorystream();
modifyimage.save(ms, imagetype);
byte[] imgdata = ms.toarray();
modifyimage.dispose();
drawedimage.dispose();
g.dispose();
filestream fs = null;
//file.delete(modifyimagepath);
fs = new filestream(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
{ }
}
}
}
}