本系列第二篇,實作「浮雕效果」:相鄰像素差值加 128 偏移,產生立體凹凸視覺錯覺。
(x,y),取右下鄰居 (x+1,y+1)。Δ = |Current - Neighbor + 128|。
private void btnEmboss_Click(object sender, EventArgs e)
{
try
{
int w = pictureBox1.Image.Width, h = pictureBox1.Image.Height;
using (var newBmp = new Bitmap(w, h))
using (var oldBmp = (Bitmap)pictureBox1.Image)
{
for (int x = 0; x < w - 1; x++)
for (int y = 0; y < h - 1; y++)
{
Color p1 = oldBmp.GetPixel(x, y);
Color p2 = oldBmp.GetPixel(x + 1, y + 1);
int r = Clamp(Math.Abs(p1.R - p2.R + 128));
int g = Clamp(Math.Abs(p1.G - p2.G + 128));
int b = Clamp(Math.Abs(p1.B - p2.B + 128));
newBmp.SetPixel(x, y, Color.FromArgb(r, g, b));
}
pictureBox1.Image = newBmp;
}
}
catch (Exception ex) { MessageBox.Show(ex.Message, "提示"); }
}
int Clamp(int v) => v < 0 ? 0 : (v > 255 ? 255 : v);

浮雕效果以簡單差值運算產生豐富立體感。理解相鄰像素關係、偏移中性灰、邊緣增強原理,可靈活設計各類非真實感渲染 (NPR) 風格。