十二、GDI+实例——浮雕(刻雕)效果
“评雕”效果的实现原理是对图像的—个像素利它左上方的那个像素之间差值的一种处理过程,处理的结果即为“浮雕”效果,这种处理是基于像素的。“浮雕”效果的算法是在相邻像素的差值上加上一个常数(为了保持图片的灰度,可以考虑给这个差值加上一个灰度常数128),使黑暗区域增加一些亮度。同时,为了避免因为差值太小而引起图片过暗或因为差值太大而引起画面过亮,在编程过程中应该对差值进行具体的控制。
所以,在编程的过程中只需要分别访问图像的每一个像素的删值,并将该RGB值与其左上方的像素进行差值运算,便能够很轻松地做出“浮雕”滤镜。需要注意的是,当设置一个像素值的时候,它和它左上方的像素都要被用到,为了避免用到已经设置过的像素,应该从图像的右下方的像素开始处理。
“雕刻”图像与“浮雕”相反,它的实现原理是,通过获取一个像素和它右下方的像素之间的差值并加上一个常数(如128),经过这样处理,就可以得到“雕刻”图像。同样需要注意的是,为了避免重复使用处理过的图像像素,处理图像时要从图像的左上方的像素开始处理。
private void button1_Click(object sender, EventArgs e)
{
Graphics graphics = this.CreateGraphics();
Bitmap bmp = new Bitmap(Application.StartupPath + "//1.jpg");
int width = bmp.Width;
int height = bmp.Height;
Bitmap bmp2 = bmp.Clone(new Rectangle(0, 0, width, height), System.Drawing.Imaging.PixelFormat.DontCare);
Color color, colorLeft;
for (int i = width - 1; i > 0; i--)
{
for (int j = height - 1; j > 0; j--)
{
color = bmp2.GetPixel(i, j);
colorLeft = bmp2.GetPixel(i - 1, j - 1);
int r = Math.Max(67, Math.Min(255, Math.Abs(color.R - colorLeft.R + 128)));
int g = Math.Max(67, Math.Min(255, Math.Abs(color.G - colorLeft.G + 128)));
int b = Math.Max(67, Math.Min(255, Math.Abs(color.B - colorLeft.B + 128)));
Color colorResult = Color.FromArgb(255, r, g, b);
bmp2.SetPixel(i, j, colorResult);
}
}
graphics.TranslateTransform(205, 0);
graphics.DrawImage(bmp2, new Rectangle(0, 0, 200, 200));
graphics.Dispose();
bmp2.Dispose();
bmp.Dispose();
}
private void button2_Click(object sender, EventArgs e)
{
Graphics graphics = this.CreateGraphics();
Bitmap bmp = new Bitmap(Application.StartupPath + "//1.jpg");
int width = bmp.Width;
int height = bmp.Height;
Bitmap bmp2 = bmp.Clone(new Rectangle(0, 0, width, height), System.Drawing.Imaging.PixelFormat.DontCare);
Color color, colorLeft;
for (int i =0;i< width - 1; i++)
{
for (int j =0;j< height - 1; j++)
{
color = bmp2.GetPixel(i, j);
colorLeft = bmp2.GetPixel(i + 1, j + 1);
int r = Math.Max(67, Math.Min(255, Math.Abs(color.R - colorLeft.R + 128)));
int g = Math.Max(67, Math.Min(255, Math.Abs(color.G - colorLeft.G + 128)));
int b = Math.Max(67, Math.Min(255, Math.Abs(color.B - colorLeft.B + 128)));
Color colorResult = Color.FromArgb(255, r, g, b);
bmp2.SetPixel(i, j, colorResult);
}
}
graphics.TranslateTransform(410, 0);
graphics.DrawImage(bmp2, new Rectangle(0, 0, 200, 200));
graphics.Dispose();
bmp2.Dispose();
bmp.Dispose();
}
本人也在学习GDI+,写得比较简单,让高手见笑了。欢迎高手给我指点
QQ:125941562