萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C# 圖片處理工具類:水印、陰影、儲存完整實作

前言

本文實作一個功能完整的 ImageModifier 類別,支援:

  • 載入來源圖片與水印圖片
  • 設定水印位置 (右下角偏移)、透明度 (0-100%)
  • 繪製水印並套用半透明色彩矩陣
  • 自動偵測輸出格式並保持原始編碼品質
  • 完整的資源釋放與異常處理

完整類別程式碼

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();

關鍵技術點解析

技術說明
ColorMatrix5x5 矩陣控制 RGBA 通道,第 4 行第 4 欄 (M[3,3]) 控制 Alpha 縮放
ImageAttributes封裝色彩調整資訊,傳給 DrawImage 實現像素級混合
Graphics 畫質屬性InterpolationMode.HighQualityBicubic 雙三次插值,縮放品質最佳
MemoryStream 緩衝避免來源檔案被鎖定導致無法覆寫
座標系統GDI+ 座標原點在左上角,X 向右,Y 向下

擴充建議

  • 支援文字水印:使用 Graphics.DrawString 或 DrawText,可動態產生版權資訊。
  • 支援圖片旋轉/翻轉:RotateFlip 方法。
  • 批次處理:實作 ApplyWatermarkBatch(IEnumerable<string> paths) 並行處理。
  • 跨平台:改用 ImageSharp (SixLabors.ImageSharp) 於 Linux/Docker 環境。
copyright © 萬盛學電腦網 all rights reserved