返回首頁
當前位置: 主頁 > 網絡編程 > .Net實例教程 >

Asp.net 上傳圖片添加半透明圖片或者文字水印的方法及代碼

時間:2013-03-04 08:55來源:知行網www.aotfjk.live 編輯:麥田守望者

主要用到System.Drawing 命名空間下的相關類,如Brush、Image、Bitmap、Graphics等等類

Image類可以從圖片文件創建Image的實例,Bitmap可以從文件也可以從已有的Image對象創建實例,而Graphics類則是封裝了對圖像的相關操作,可以理解為一個繪圖的面板,在這個面板里你可以添加文字,添加背景等等很多常規繪圖軟件具備的功能。

下面就怎樣添加水印做簡單的介紹:

為了方便理解我把水印分為文字型的水印以及圖片型的水印,它們都派生自WatermarkPainter基類,需要實現基類中的AddWatermark的方法,這個方法是用來具體的繪圖用。

WatermarkPainter類如下:

/* ***********************************************
* NameSpace: Juice.Common.Drawing
* Class/Interface: WatermarkPainter
* ***********************************************/

using System.Drawing;
using System.IO;
using System.Text;
using System;

namespace Juice.Common.Drawing
{
/// <summary>
/// 圖片水印繪制器
/// </summary>
public abstract class WatermarkPainter : IDisposable
{
/// <summary>
/// 構造函數
/// </summary>
/// <param name="rawImagePath"></param>
/// <param name="alpha"></param>
/// <param name="replaceRawImage"></param>
protected WatermarkPainter(string rawImagePath, int alpha, bool replaceRawImage)
{
ImageToBePainted = rawImagePath;
WatermarkAlpha = alpha;
ReplaceRawImage = replaceRawImage;
}

/// <summary>
/// 構造函數
/// </summary>
/// <param name="rawImagePath"></param>
/// <param name="alpha"></param>
protected WatermarkPainter(string rawImagePath, int alpha)
: this(rawImagePath, alpha, true)
{ }

/// <summary>
/// 為臨時存儲文件添加的后綴
/// </summary>
private string m_TempFileSuffix = ".juice.watermark.temp";

/// <summary>
/// 水印的透明度
/// </summary>
private int m_WatermarkAlpha;

/// <summary>
/// 水印透明度
/// </summary>
public int WatermarkAlpha
{
get
{
if (m_WatermarkAlpha > 255)
m_WatermarkAlpha = 255;
else if (m_WatermarkAlpha < 0)
m_WatermarkAlpha = 0;
return m_WatermarkAlpha;
}
set { m_WatermarkAlpha = value; }
}

private string m_ImageToBePainted;

/// <summary>
/// 添加水印的圖片的物理路徑
/// </summary>
public string ImageToBePainted
{
get { return m_ImageToBePainted; }
set { m_ImageToBePainted = value; }
}

private bool m_ReplaceRawImage;

/// <summary>
/// 是否用加了水印的圖片替換原有的圖片
/// </summary>
public bool ReplaceRawImage
{
get { return m_ReplaceRawImage; }
set { m_ReplaceRawImage = value; }
}

private string m_TempImagePath;

/// <summary>
/// 加了水印后的臨時儲存名稱
/// </summary>
protected string TempImagePath
{
get
{
if (string.IsNullOrEmpty(this.m_TempImagePath))
{
StringBuilder s = new StringBuilder(ImageToBePainted);
s.Append(this.m_TempFileSuffix);
this.m_TempImagePath = s.ToString();
}
return m_TempImagePath;
}
set { m_TempImagePath = value; }
}

/// <summary>
/// 原始圖像
/// </summary>
private Image m_RawImage;

/// <summary>
/// 為圖片添加水印
/// </summary>
public void PaintWaterMark()
{
if (string.IsNullOrEmpty(ImageToBePainted))
return;
if (!File.Exists(ImageToBePainted))
throw new FileNotFoundException(string.Format("file {0} not found.", ImageToBePainted));
bool succeed;
if (m_RawImage == null)
m_RawImage = Image.FromFile(ImageToBePainted);
///原始的圖片
using (Bitmap newImage = new Bitmap(m_RawImage.Width, m_RawImage.Height))
{
///創建繪制圖片的圖面
using (Graphics g = Graphics.FromImage(newImage))
{
g.DrawImage(m_RawImage, 0, 0, m_RawImage.Width, m_RawImage.Height);
///開始繪制水印
succeed = AddWatermark(g, newImage);
}
if (succeed)
///將圖片保存到臨時的文件
newImage.Save(TempImagePath);
if (m_RawImage != null)
m_RawImage.Dispose();
}
if (succeed && ReplaceRawImage)
{
//刪除原來的文件
if (File.Exists(ImageToBePainted))
File.Delete(ImageToBePainted);
FileInfo info = new FileInfo(TempImagePath);
if (info.Exists)
{
info.MoveTo(ImageToBePainted);
}
}

}

/// <summary>
/// 添加水印,繼承類可以用來添加自己的水印
/// </summary>
/// <param name="graphics"></param>
/// <param name="newImage"></param>
/// <returns></returns>
protected abstract bool AddWatermark(Graphics graphics, Bitmap newImage);

#region IDisposable 成員

public virtual void Dispose()
{

}

#endregion
}
}

而文字型的水印的類是TextWatermarkPainter類

/* ***********************************************
* Author: 1987raymond
* Team: Juice Sharing
* Created Time: 2009-3-11 15:15:16
* CopyRight: Juice Sharing 團隊版權所有 保留一切權利
* NameSpace: Juice.Common.Drawing
* Class/Interface: TextWatermarkPainter
* ***********************************************/

using System.Drawing;
using System.IO;
using System.Text;
using System;

namespace Juice.Common.Drawing
{
/// <summary>
/// 添加文字水印
/// </summary>
public sealed class TextWatermarkPainter : WatermarkPainter
{
/// <summary>
/// 構造函數
/// </summary>
/// <param name="rawImagePath"></param>
/// <param name="alpha"></param>
/// <param name="text"></param>
public TextWatermarkPainter(string rawImagePath, int alpha, string text)
: base(rawImagePath, alpha)
{
WatermarkText = text;
}

private Font m_Font;

/// <summary>
/// 水印文字的字體
/// </summary>
public Font Font
{
get
{
if (null == m_Font)
m_Font = new Font("Arial Black", 14, FontStyle.Bold, GraphicsUnit.Pixel);
return m_Font;
}
set { m_Font = value; }
}

private Color m_FontColor;

/// <summary>
/// 字體顏色
/// </summary>
public Color FontColor
{
get
{
if (m_FontColor == null)
m_FontColor = Color.DarkSeaGreen;
return m_FontColor;
}
set { m_FontColor = value; }
}

private string m_WatermarkText;

/// <summary>
/// 水印的文字
/// </summary>
public string WatermarkText
{
get { return m_WatermarkText; }
set { m_WatermarkText = value; }
}

/// <summary>
/// 實現添加水印的方法
/// </summary>
/// <param name="graphics"></param>
/// <param name="newImage"></param>
/// <returns></returns>
protected override bool AddWatermark(Graphics graphics, Bitmap newImage)
{
if (string.IsNullOrEmpty(WatermarkText))
return true;
using (SolidBrush brush = new SolidBrush(Color.FromArgb(WatermarkAlpha, FontColor.R, FontColor.G, FontColor.B)))
{
Font font;
///添加文字位置
PointF f = new PointF();
float totalWidth = Font.Size * WatermarkText.Length;
f.X = newImage.Width - totalWidth - 100;
f.Y = newImage.Height - Font.Height;
if (f.X < 0)
{
///自動調整字體的大小
float width = newImage.Width / WatermarkText.Length;
font = new Font(Font.FontFamily, width, GraphicsUnit.Pixel);
}
else
font = Font;
graphics.DrawString(WatermarkText, font, brush, f);
}
return true;
}

#region IDisposable 成員

public override void Dispose()
{
Font.Dispose();
base.Dispose();
}

#endregion
}
}

 

下面是對文字型水印的測試:

default.aspx內容如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
< html xmlns="http://www.w3.org/1999/xhtml">
< head runat="server">
<title>無標題頁</title>
< /head>
< body>
<form id="form1" runat="server">
<div>
水印文字:<asp:TextBox ID="watermarkTextBox" runat="server"></asp:TextBox><br />
選擇上傳圖片:<asp:FileUpload ID="FileUpload1" runat="server" Width="189px" />
<br />
<asp:Button ID="uploadFileBtn" runat="server" Text="上傳圖片并且加文字水印"
onclick="uploadFileBtn_Click" />
<br />加了水印的圖像如下:
<asp:Image ID="image" runat="server" />
</div>
</form>
< /body>
< /html>

default.aspx.cs代碼如下:

using System;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Juice.Common.Drawing;
using System.Web.Hosting;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void uploadFileBtn_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(this.watermarkTextBox.Text))
return;
if (FileUpload1.HasFile)
{
string contentType = FileUpload1.PostedFile.ContentType;
if (contentType.StartsWith("image/"))
{
string filePath = Server.MapPath(string.Format("~/{0}", FileUpload1.FileName));
///保存文件
FileUpload1.SaveAs(filePath);
///加水印
this.AddWatermark(filePath, this.watermarkTextBox.Text);
image.ImageUrl = string.Format("~/{0}", FileUpload1.PostedFile.FileName);
}
}
}

/// <summary>
/// 添加水印
/// </summary>
/// <param name="filePath"></param>
/// <param name="watermaterText"></param>
private void AddWatermark(string filePath, string watermaterText)
{
using (TextWatermarkPainter painter = new TextWatermarkPainter(filePath, 80, watermaterText))
{
painter.FontColor = System.Drawing.Color.DarkGreen;
painter.PaintWaterMark();
}

}
}

------分隔線----------------------------
標簽(Tag):C# C#實例教程 c#基礎教程 C#源代碼 c#技巧
------分隔線----------------------------
推薦內容
猜你感興趣
湖南刘雪龙黑彩