public enum WaterMarkType { TextMark /*, ImageMark */ }
public enum WaterMarkPosition { LeftTop, LeftBottom, RightTop, RightBottom }
public class ImageWaterMark
{
// 公開進入點
public void AddWaterMark(string oldPath, string newPath, WaterMarkType type, string content)
// 內部實作
private void AddWatermarkText(Graphics g, string text, string position, int width, int height)
private void AddWatermarkImage(Graphics g, Image watermark, string position, int width, int height)
private void AddWatermarkImage(Graphics g, string imgPath, string position, int width, int height)
// 縮圖功能
public void ToThumbnailImages(string source, string dest, int thumbWidth)
}
int[] sizes = {32,30,28,26,24,22,20,18,16,14,12,10,8,6,4};
Font font = null; SizeF size;
for (int i=0; i
Bitmap shadowBmp = new Bitmap((int)size.Width+3, (int)size.Height+3, PixelFormat.Format32bppArgb);
Graphics fg = Graphics.FromImage(shadowBmp);
Brush blackBrush = new SolidBrush(Color.FromArgb(255, Color.Black));
Brush grayBrush = new SolidBrush(Color.FromArgb(255, Color.Black)); // 可調透明度
// 多偏移繪製形成陰影
fg.DrawString(text, font, blackBrush, 0, 1);
fg.DrawString(text, font, blackBrush, 1, 0);
fg.DrawString(text, font, grayBrush, 1, 1);
fg.DrawString(text, font, grayBrush, 0, 2);
fg.DrawString(text, font, grayBrush, 2, 0);
// 最後繪製白色主文字
fg.DrawString(text, font, new SolidBrush(Color.White), 0, 0);
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,0.3f,0}, // Alpha 縮放 0.3 = 30% 不透明
new float[]{0,0,0,0,1}
});
ImageAttributes ia = new ImageAttributes();
ia.SetColorMatrix(cm, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
g.DrawImage(watermark, destRect, 0,0, watermark.Width, watermark.Height, GraphicsUnit.Pixel, ia);
double ratio = (double)thumbWidth / image.Width;
int thumbHeight = (int)(image.Height * ratio);
// 高品質插值
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(image, 0, 0, thumbWidth, thumbHeight);
var wm = new ImageWaterMark();
wm.AddWaterMark(@"C:\src.jpg", @"C:\dst.jpg", WaterMarkType.TextMark, "Copyright © 2024");
wm.ToThumbnailImages(@"C:\src.jpg", @"C:\thumb.jpg", 200);
結合 Graphics 繪圖、ColorMatrix 色彩調整、ImageAttributes 影像屬性,即可構建專業級的水印與縮圖元件。程式碼已模組化,易於整合至 ASP.NET Core、WPF 或桌面應用的圖片處理管線中。