程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> ASP.NET基礎 >> C# 添加圖片水印類實現代碼

C# 添加圖片水印類實現代碼

編輯:ASP.NET基礎
復制代碼 代碼如下:
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
{ }
}
}
}
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved