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();
            }
        }
相关推荐
weixin_4474432510 分钟前
AI启蒙Lean4
python·c#
我是唐青枫4 小时前
C#.NET ValueTaskSource 深入解析:零分配异步、ManualResetValueTaskSourceCore 与使用边界
c#·.net
iCxhust4 小时前
C#程序,窗体1向窗体2的textbox控件写入字符串“hello”
开发语言·c#
iCxhust5 小时前
C#如何实现textbox文本多行输出 且自动换行输出
开发语言·c#
政沅同学7 小时前
C# 一种很好用的设计模式 不同对象之间进行解耦通信
设计模式·c#
咩图8 小时前
C#进程通讯-命名管道通讯
c#·命名管道·进程通讯
SunnyDays10119 小时前
如何使用 C# 高效实现 Excel 与 CSV 的互相转换
c#·excel·csv
Byron Loong9 小时前
【网络】C#TCP 通讯
网络·tcp/ip·c#
geovindu9 小时前
密码进行加盐哈希 using CSharp,Python,Go,Java
java·python·golang·c#·哈希算法
傻啦嘿哟9 小时前
Python 操作 Word 文档属性与字数统计方法详解
开发语言·c#