Image类可以从图片文件创建Image的实例,Bitmap可以从文件也可以从已有的Image对象创建实例,而Graphics类则是封装了对图像的相关操作,可以理解为一个绘图的面板,在这个面板里你可以添加文字,添加背景等等很多常规绘图软件具备的功能。
下面就怎样添加水印做简单的介绍:
为了方便理解我把水印分为文字型的水印以及图片型的水印,它们都派生自WatermarkPainter基类,需要实现基类中的AddWatermark的方法,这个方法是用来具体的绘图用。
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 (!System.IO.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);
///开始绘制水印