当前位置: 移动技术网 > IT编程>开发语言>.net > C# 添加图片水印类实现代码

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

2017年12月12日  | 移动技术网IT编程  | 我要评论

青岛交友,办公桌二人组,爱在飞 电视剧

复制代码 代码如下:

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
{ }
}
}
}
}

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网