本文實作一個功能完整的 ImageModifier 類別,支援:
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
namespace CLB.Utility.Tools
{
public class ImageModifier : IDisposable
{
#region 屬性
public string SourceImagePath { get; set; }
public string WatermarkImagePath { get; set; }
public int RightMargin { get; set; } = 10;
public int BottomMargin { get; set; } = 10;
public int OpacityPercent { get; set; } = 70; // 0-100
public string OutputPath { get; set; }
#endregion
#region 公用方法
///
/// 執行水印繪製並儲存
///
public void ApplyWatermark()
{
if (string.IsNullOrWhiteSpace(SourceImagePath) || !File.Exists(SourceImagePath))
throw new FileNotFoundException("來源圖片不存在", SourceImagePath);
if (string.IsNullOrWhiteSpace(WatermarkImagePath) || !File.Exists(WatermarkImagePath))
throw new FileNotFoundException("水印圖片不存在", WatermarkImagePath);
if (OpacityPercent < 0 || OpacityPercent > 100)
throw new ArgumentOutOfRangeException(nameof(OpacityPercent), "透明度需在 0-100 之間");
Image source = null, watermark = null;
Graphics g = null;
MemoryStream ms = null;
FileStream fs = null;
try
{
source = Image.FromFile(SourceImagePath);
watermark = Image.FromFile(WatermarkImagePath);
// 計算繪製位置 (右下角)
int x = source.Width - watermark.Width - RightMargin;
int y = source.Height - watermark.Height - BottomMargin;
if (x < 0) x = 0;
if (y < 0) y = 0;
g = Graphics.FromImage(source);
g.CompositingQuality = CompositingQuality.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
// 建立半透明色彩矩陣
float alpha = OpacityPercent / 100f;
ColorMatrix cm = new ColorMatrix(new float[][]
{
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,alpha,0},
new float[] {0,0,0,0,1}
});
ImageAttributes ia = new ImageAttributes();
ia.SetColorMatrix(cm, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
// 繪製水印
g.DrawImage(watermark,
new Rectangle(x, y, watermark.Width, watermark.Height),
0, 0, watermark.Width, watermark.Height,
GraphicsUnit.Pixel, ia);
// 決定輸出格式
ImageFormat fmt = GetImageFormat(SourceImagePath);
string outPath = string.IsNullOrWhiteSpace(OutputPath) ? SourceImagePath : OutputPath;
// 先存到 MemoryStream,再寫入檔案,避免檔案被佔用無法覆寫
ms = new MemoryStream();
source.Save(ms, fmt);
byte[] data = ms.ToArray();
// 若覆寫原檔,先刪除
if (outPath == SourceImagePath && File.Exists(outPath))
File.Delete(outPath);
fs = new FileStream(outPath, FileMode.Create, FileAccess.Write);
fs.Write(data, 0, data.Length);
}
finally
{
ms?.Dispose();
fs?.Dispose();
g?.Dispose();
watermark?.Dispose();
source?.Dispose();
}
}
#endregion
#region 私有輔助
private static ImageFormat GetImageFormat(string path)
{
string ext = Path.GetExtension(path).ToLowerInvariant();
return ext switch
{
".jpg" or ".jpeg" => ImageFormat.Jpeg,
".png" => ImageFormat.Png,
".gif" => ImageFormat.Gif,
".bmp" => ImageFormat.Bmp,
".tif" or ".tiff" => ImageFormat.Tiff,
".wmf" => ImageFormat.Wmf,
".ico" => ImageFormat.Icon,
_ => ImageFormat.Png
};
}
#endregion
#region IDisposable
public void Dispose() { /* 無非受控資源 */ }
#endregion
}
}
var modifier = new ImageModifier
{
SourceImagePath = @"C:\Images\photo.jpg",
WatermarkImagePath = @"C:\Images\logo.png",
RightMargin = 20,
BottomMargin = 20,
OpacityPercent = 50,
OutputPath = @"C:\Images\photo_watermarked.jpg"
};
modifier.ApplyWatermark();
| 技術 | 說明 |
|---|---|
| ColorMatrix | 5x5 矩陣控制 RGBA 通道,第 4 行第 4 欄 (M[3,3]) 控制 Alpha 縮放 |
| ImageAttributes | 封裝色彩調整資訊,傳給 DrawImage 實現像素級混合 |
| Graphics 畫質屬性 | InterpolationMode.HighQualityBicubic 雙三次插值,縮放品質最佳 |
| MemoryStream 緩衝 | 避免來源檔案被鎖定導致無法覆寫 |
| 座標系統 | GDI+ 座標原點在左上角,X 向右,Y 向下 |
Graphics.DrawString 或 DrawText,可動態產生版權資訊。RotateFlip 方法。ApplyWatermarkBatch(IEnumerable<string> paths) 並行處理。SixLabors.ImageSharp) 於 Linux/Docker 環境。