下面是ImageWatermarkPainter类的实现:
using System;
using System.Text;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
namespace Juice.Common.Drawing
{
/// <summary>
/// 图片水印绘制器
/// </summary>
public sealed class ImageWatermarkPainter : WatermarkPainter
{
/// <summary>
/// 构造函数
/// </summary>
/// <param name="rawImagePath"></param>
/// <param name="alpha"></param>
/// <param name="watermarkImage"></param>
public ImageWatermarkPainter(string rawImagePath, int alpha, string watermarkImage)
: base(rawImagePath, alpha)
{
WatermarkImagePath = watermarkImage;
}
private string m_WatermarkImagePath;
/// <summary>
/// 水印图片路径
/// </summary>
public string WatermarkImagePath
{
get { return m_WatermarkImagePath; }
set { m_WatermarkImagePath = value; }
}
private Image m_WatermarkImage;
/// <summary>
/// 水印图片对象
/// </summary>
public Image WatermarkImage
{
get
{
if (null == m_WatermarkImage)
m_WatermarkImage = Image.FromFile(WatermarkImagePath);
return m_WatermarkImage;
}
}
/// <summary>
/// 添加水印
/// </summary>
/// <param name="graphics"></param>
/// <param name="newImage"></param>
/// <returns></returns>
protected override bool AddWatermark(Graphics graphics, Bitmap newImage)
{
if (string.IsNullOrEmpty(WatermarkImagePath))
return false;
if (!System.IO.File.Exists(WatermarkImagePath))
throw new FileNotFoundException(string.Format("file {0} not found.", WatermarkImagePath));
if ((WatermarkImage.Width + 10) > newImage.Width || (WatermarkImage.Height + 10) > newImage.Height)
return false;
using (ImageAttributes attributes = new ImageAttributes())
{
float alpha = WatermarkAlpha / 255.0f;
float[][] colorMatrixElements = {
new float[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f},
new float[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f},
new float[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f},
new float[] {0.0f, 0.0f, 0.0f, alpha, 0.0f},
new float[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}
};
ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);
///设置颜色调整矩阵
attributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);