【C#】Bitmap图像实现背景透明

/// <summary>
/// 背景透明化
/// </summary>
/// <param name="img">原图</param>
/// <returns></returns>
public static Bitmap ConverImageBackTransparent(Bitmap img)
{
    Bitmap bg = new Bitmap(img.Width, img.Height);
    try
    {
        int alpha = 0;
        Color demo;
        Color pixel;
        for (int x = 0; x < img.Width; x++)
        {
            for (int y = 0; y < img.Height; 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));
            }
        }
    }
    catch (Exception ex)
    {
        
    }
    return bg;
}
posted @ 2024-08-28 08:39  qiutian-hao  阅读(55)  评论(0编辑  收藏  举报