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();
            }
        }
相关推荐
bianguanyue4 小时前
SQLite密码修改故障排查:RSA加密随机性导致的数据库匹配问题
数据库·sqlite·c#
R-sz4 小时前
导出word并且插入图片
开发语言·c#·word
CodeCraft Studio9 小时前
PPT处理控件Aspose.Slides教程:使用 C# 将 PPTX 转换为 EMF
c#·powerpoint·ppt·aspose·ppt格式转换
future141210 小时前
游戏开发日记7.12
数据结构·学习·c#·游戏开发
洁辉10 小时前
C# & .NET 面试深度复习指南
面试·c#·.net
_oP_i12 小时前
无法找到来自源 EdgeWebView,实际安装了,偶尔出现
c#
阿蒙Amon13 小时前
C#类型转换:从基础到进阶的全景解析
开发语言·c#
时光追逐者19 小时前
一款开源免费、通用的 WPF 主题控件包
开源·c#·.net·wpf
张人玉1 天前
c#中Random类、DateTime类、String类
开发语言·c#
future14121 天前
游戏开发日记
数据结构·学习·c#