【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 @   qiutian-hao  阅读(121)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
点击右上角即可分享
微信分享提示