c# 设置图片透明度

逐个像素进行Alpha值的设置,网上其他的代码不能处理有透明背景的图片,因此要对Alpha、R、G、B均为0的透明色进行特殊处理,不做转换。

cs 复制代码
        private Bitmap SetImageOpacity(Image srcImage, int opacity)
        {
            Bitmap pic = new Bitmap(srcImage);
            for (int w = 0; w < pic.Width; w++)
            {
                for (int h = 0; h < pic.Height; h++)
                {
                    Color c = pic.GetPixel(w, h);
                    Color newC;
                    if (!c.Equals(Color.FromArgb(0, 0, 0, 0)))
                    {
                        newC = Color.FromArgb(opacity, c);
                    }
                    else
                    {
                        newC = c;
                    }
                    pic.SetPixel(w, h, newC);
                }
            }
            return pic;
        }

        private Image SetImageOpacity2(Image srcImage, int opacity)
        {
            Bitmap img = new Bitmap(srcImage);
            using (Bitmap bmp = new Bitmap(img.Width, img.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb))
            {
                using (Graphics g = Graphics.FromImage(bmp))
                {
                    g.DrawImage(img, 0, 0);
                    for (int h = 0; h <= img.Height - 1; h++)
                    {
                        for (int w = 0; w <= img.Width - 1; w++)
                        {
                            Color c = img.GetPixel(w, h);
                            if (!c.Equals(Color.FromArgb(0, 0, 0, 0)))
                            {
                                bmp.SetPixel(w, h, Color.FromArgb(opacity, c.R, c.G, c.B));
                            }
                            else
                            {
                                bmp.SetPixel(w, h, Color.FromArgb(c.A, c.R, c.G, c.B));
                            }
                        }
                    }
                }
                return (Image)bmp.Clone();
            }
        }
相关推荐
lljss20205 小时前
C# 从代码创建选型卡+表格
c#
weixin_307779135 小时前
使用C#配置信息类的属性生成Snowflake CREATE STAGE语句
开发语言·数据仓库·hive·c#
唐青枫6 小时前
C# virtual 和 abstract 详解
c#·.net
闪电麦坤9510 小时前
C#:is关键字
开发语言·c#
BuHuaX12 小时前
C#的反射机制
服务器·unity·c#·游戏引擎·游戏程序
痛&快乐着14 小时前
C#调用C++动态库时出现`System.DllNotFoundException`错误的解决思路
c++·c#
C#沐清玄(编程小白)14 小时前
c#程序结构
开发语言·c#
Crazy Struggle17 小时前
C# 工业视觉开发必刷20道 Halcon 面试题
c#·自动化·halcon
江沉晚呤时18 小时前
C# 状态模式深度解析:构建灵活的状态驱动系统
开发语言·javascript·数据库·ui·ajax·c#·ecmascript
hez20101 天前
用 .NET NativeAOT 构建完全 distroless 的静态链接应用
c#·.net·aot·.net core·native