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();
            }
        }
相关推荐
江山如画,佳人北望6 小时前
C#程序入门
开发语言·windows·c#
与火星的孩子对话7 小时前
Unity进阶课程【六】Android、ios、Pad 终端设备打包局域网IP调试、USB调试、性能检测、控制台打印日志等、C#
android·unity·ios·c#·ip
future14127 小时前
C#每日学习日记
java·学习·c#
军训猫猫头10 小时前
1.如何对多个控件进行高效的绑定 C#例子 WPF例子
开发语言·算法·c#·.net
葬歌倾城1 天前
JSON的缩进格式方式和紧凑格式方式
c#·json
Eiceblue1 天前
使用 C# 发送电子邮件(支持普通文本、HTML 和附件)
开发语言·c#·html·visual studio
小小小小王王王1 天前
hello判断
开发语言·c#
金增辉1 天前
基于C#的OPCServer应用开发,引用WtOPCSvr.dll
c#
future14121 天前
C#学习日记
开发语言·学习·c#
傻啦嘿哟1 天前
Python 办公实战:用 python-docx 自动生成 Word 文档
开发语言·c#