C#中图片新增水印

/// <summary>
/// 在图片上生成图片水印
/// </summary>
/// <param name="Path">原服务器图片路径</param>
/// <param name="Path_syp">生成的带图片水印的图片路径</param>
/// <param name="Path_sypf">水印图片路径</param>
public static void AddWaterPic(string Path, string Path_syp, string Path_sypf,int x=0,int y=0)
{
using (Image srcImg = Image.FromFile(Path))
{
//将水印文件加载到内存中
using (Image waterMark = Image.FromFile(Path_sypf))
{
//实例化一块画布
using (Graphics g = Graphics.FromImage(srcImg))
{

if (x == 0)
{
x = (int)(((double)srcImg.Width - (double)waterMark.Width) / 2);

}
if (y == 0)
{
y = (int)(((double)srcImg.Height - ((double)waterMark.Height / 2)) / 2);
}
//写文字
//g.DrawString("17cn商城版权所有...",new Font("Microsoft Yahei",20),new SolidBrush(Color.Red),20,20);
//画图片

//按图片大小给定水印
//if (srcImg.Width > 100000000)
//{
// Path_sypf = Path_sypf.Replace("logo_1.png", "logo_1.png");
//}
//else if(srcImg.Width > 500000)
//{
// Path_sypf = Path_sypf.Replace("logo_1.png", "logo_1.png");
//}

//水印的宽度大于图片宽度时进行水印压缩
if (waterMark.Width > srcImg.Width)
{
x = 0;
int waterh = (int)((double)srcImg.Width / (double)waterMark.Width * (double)waterMark.Height);
g.DrawImage(waterMark.GetThumbnailImage(srcImg.Width,waterh , null, IntPtr.Zero), new Rectangle(x, y, waterMark.Width, waterMark.Height), 0, 0, waterMark.Width, waterMark.Height, GraphicsUnit.Pixel);
}
else
{
g.DrawImage(waterMark, new Rectangle(x, y, waterMark.Width, waterMark.Height), 0, 0, waterMark.Width, waterMark.Height, GraphicsUnit.Pixel);
}
srcImg.Save(Path_syp);
}
}

}

posted @ 2016-12-29 17:31  李文平  阅读(890)  评论(0编辑  收藏  举报