public class ImageUtil
{
/// <summary>
/// 检查RGB值ed有效范围
/// </summary>
/// <param name="rgb"></param>
/// <returns></returns>
private static int verifyRGB(int rgb)
{
if (rgb < 0)
return 0;
if (rgb > 255)
return 255;
return rgb;
}
/// <summary>
/// 反色处理
/// </summary>
/// <param name="bmp"></param>
public static Bitmap FilterInverse(Bitmap bmp)
{
Bitmap result = new Bitmap(bmp.Width, bmp.Height);
Color pixel;
for (int x = 0; x < bmp.Width; x++)
{
for (int y = 0; y < bmp.Height; y++)
{
pixel = bmp.GetPixel(x, y);
result.SetPixel(x, y, Color.FromArgb(255 - pixel.R, 255 - pixel.G, 255 - pixel.B));
}
}
return result;
}
/// <summary>
/// 浮雕处理
/// </summary>
/// <param name="bmp"></param>
public static Bitmap FilterEmbossment(Bitmap bmp)
{
Bitmap result = new Bitmap(bmp.Width, bmp.Height);
Color color1, color2;
int r = 0, g = 0, b = 0;
for (int x = 0; x < bmp.Width - 1; x++)
{
for (int y = 0; y < bmp.Height - 1; y++)
{
color1 = bmp.GetPixel(x, y);
color2 = bmp.GetPixel(x + 1, y + 1);
r = Math.Abs(color1.R - color2.R + 128);
g = Math.Abs(color1.G - color2.G + 128);
b = Math.Abs(color1.B - color2.B + 128);
result.SetPixel(x, y, Color.FromArgb(verifyRGB(r), verifyRGB(g), verifyRGB(b)));
}
}
return result;
}
/// <summary>
/// 滤色处理
/// </summary>
/// <param name="bmp"></param>
public static Bitmap FilterColour(Bitmap bmp)
{
Bitmap result = new Bitmap(bmp.Width, bmp.Height);
Color pixel;
for (int x = 0; x < bmp.Width; x++)
{
for (int y = 0; y < bmp.Height; y++)
{
pixel = bmp.GetPixel(x, y);
result.SetPixel(x, y, Color.FromArgb(0, pixel.G, pixel.B));
}
}
return result;
}
/// <summary>
/// 黑白处理
/// </summary>
/// <param name="bmp"></param>
public static Bitmap FilterBlackWhite(Bitmap bmp)
{
Bitmap result = new Bitmap(bmp.Width, bmp.Height);
Color pixel;
int val;
for (int x = 0; x < bmp.Width; x++)
{
for (int y = 0; y < bmp.Height; y++)
{
pixel = bmp.GetPixel(x, y);
val = (pixel.R + pixel.G + pixel.B) / 3;
result.SetPixel(x, y, Color.FromArgb(val, val, val));
}
}
return result;
}
/// <summary>
/// 亮度处理
/// </summary>
/// <param name="bmp"></param>
/// <param name="val">增加或减少亮度(-255至255)</param>
public static Bitmap FilterLightness(Bitmap bmp, int val)
{
Bitmap result = new Bitmap(bmp.Width, bmp.Height);
Color pixel;
for (int x = 0; x < bmp.Width; x++)
{
for (int y = 0; y < bmp.Height; y++)
{
pixel = bmp.GetPixel(x, y);
result.SetPixel(x, y, Color.FromArgb(verifyRGB(pixel.R + val), verifyRGB(pixel.G + val), verifyRGB(pixel.B + val)));
}
}
return result;
}
/// <summary>
/// 透明度处理
/// </summary>
/// <param name="bmp"></param>
/// <param name="val">透明度(0-255)</param>
public static Bitmap FilterTransparent(Bitmap bmp, int val)
{
Bitmap result = new Bitmap(bmp.Width, bmp.Height);
Color pixel;
for (int x = 0; x < bmp.Width; x++)
{
for (int y = 0; y < bmp.Height; y++)
{
pixel = bmp.GetPixel(x, y);
result.SetPixel(x, y, Color.FromArgb(val, pixel.R, pixel.G, pixel.B));
}
}
return result;
}
}