Bitmap 對象或保存為 PNG (保留 Alpha 通道)。int size = 300; // 印章直徑像素
Bitmap stamp = new Bitmap(size, size, PixelFormat.Format32bppArgb);
using (Graphics g = Graphics.FromImage(stamp)) {
g.Clear(Color.Transparent); // 關鍵:透明背景
g.SmoothingMode = SmoothingMode.AntiAlias; // 抗鋸齒
}
using (Graphics g = Graphics.FromImage(stamp)) {
// 外圓
using (Pen pen = new Pen(Color.FromArgb(200, 180, 0, 0), 8)) { // 深紅、半透明
g.DrawEllipse(pen, 4, 4, size - 8, size - 8);
}
// 五角星 (中心)
DrawStar(g, size/2, size/2, 50, Color.FromArgb(200, 180, 0, 0));
// 文字 (繞圓或水平)
DrawCircularText(g, "單位名稱", size/2, size/2, 100, Color.Red);
}
// 像素級處理:隨機將部分像素設置為透明/半透明
Random rnd = new Random();
for (int y = 0; y < size; y++) {
for (int x = 0; x < size; x++) {
Color c = stamp.GetPixel(x, y);
if (c.A > 0) { // 非透明像素
// 30% 概率降低透明度,模擬油墨缺失
if (rnd.NextDouble() < 0.3) {
int newAlpha = (int)(c.A * (0.3 + rnd.NextDouble() * 0.5)); // 30%-80%
stamp.SetPixel(x, y, Color.FromArgb(newAlpha, c.R, c.G, c.B));
}
// 5% 概率完全透明 (磨損)
else if (rnd.NextDouble() < 0.05) {
stamp.SetPixel(x, y, Color.Transparent);
}
}
}
}
性能優化:使用 Bitmap.LockBits 直接操作內存,避免 GetPixel/SetPixel 極慢。
public void StampOnDocument(string docPath, string outputPath, Point location) {
using (Image doc = Image.FromFile(docPath))
using (Graphics g = Graphics.FromImage(doc))
using (Bitmap stamp = GenerateStamp()) {
g.DrawImage(stamp, location); // 直接疊加,透明背景自動混合
doc.Save(outputPath, ImageFormat.Png); // 或 PDF 需用 PdfSharp 等庫
}
}
stamp = GaussianBlur(stamp, 1.5f); 模擬油墨擴散。Multiply 混合模式疊加。PathGradientBrush 實現。C# 生成逼真印章核心流程:透明畫布 → 矢量繪製基礎形狀 → 像素級隨機透明化模擬質感 → LockBits 加速 → DrawImage 疊加。關鍵在Format32bppArgb 保證透明通道與隨機演算法模擬真實油墨缺陷。代碼模塊化後,可輕松擴展不同樣式、尺寸、顏色的印章生成器。