以下的代码都经过测试通过了的
/// <summary>
/// 背景透明化
/// </summary>
/// <param name="img">原图</param>
/// <param name="w">图片宽度</param>
/// <param name="h">图片高度</param>
/// <returns></returns>
public static Bitmap Conver_1(Bitmap img, int w, int h)
{
Bitmap bg = new Bitmap(w, h);
int alpha = 0;
Color demo;
Color pixel;
for (int x = 0; x < w; x++)
{
for (int y = 0; y < h; y++)
{
demo = img.GetPixel(1, 1);
pixel = img.GetPixel(x, y);
int R = demo.R;
int G = demo.G;
int B = demo.B;
int r1 = pixel.R;
int g1 = pixel.G;
int b1 = pixel.B;
int a = 40; //RGB误差范围
if (Math.Abs(R - r1) < a && Math.Abs(G - g1) < a && Math.Abs(B - b1) < a)
{
alpha = 0; //RGB在色差范围内,透明度为0
}
else
{
alpha = 255;
}
bg.SetPixel(x, y, Color.FromArgb(alpha, r1, g1, b1));
}
}
return bg;
}
/// <summary>
/// 指定颜色透明化
/// </summary>
/// <param name="img">原图</param>
/// <param name="w">原图宽度</param>
/// <param name="h">原图高度</param>
/// <param name="R">指定颜色RGB的R值</param>
/// <param name="G">指定颜色RGB的G值</param>
/// <param name="B">指定颜色RGB的B值</param>
/// <returns></returns>
public static Bitmap Conver_2(Bitmap img, int w, int h, int R, int G, int B)
{
Bitmap bg = new Bitmap(w, h);
int alpha = 0;
Color pixel;
for (int x = 0; x < w; x++)
{
for (int y = 0; y < h; y++)
{
pixel = img.GetPixel(x, y);
int r1 = pixel.R;
int g1 = pixel.G;
int b1 = pixel.B;
int a = 40; //色差范围值
if (Math.Abs(R - r1) < a && Math.Abs(G - g1) < a && Math.Abs(B - b1) < a)
{
alpha = 0; //若两种颜色比较接近,透明度设为0
}
else
{
alpha = 255;
}
bg.SetPixel(x, y, Color.FromArgb(alpha, r1, g1, b1));
}
}
return bg;
}
/// <summary>
/// 指定颜色替换成另一种颜色
/// </summary>