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();
            }
        }
相关推荐
m5655bj18 小时前
如何使用 Python 转换 Excel 工作表到 PDF 文档
开发语言·c#·excel
技术支持者python,php19 小时前
SUB设备电子狗加密狗开发
c#
唐青枫21 小时前
循环插入太慢?试试 C#.NET SqlBulkCopy,一次导入上百万数据
c#·.net
SmoothSailingT1 天前
C#窗体—子窗体获取父窗体TextBox框的值
c#·窗体
ysdysyn1 天前
C# 进程管理实战:检查与启动EXE程序的完整指南
开发语言·c#
云缘若仙1 天前
Godot游戏开发——C# (一)
c#·godot
花北城1 天前
【C#】List快速检查重复数据
开发语言·c#
sky-stars1 天前
.NET 泛型编程(泛型类、泛型方法、泛型接口、泛型委托、泛型约束)
c#·.net·.netcore
yue0081 天前
C# 类的属性介绍
c#·属性·
sali-tec2 天前
C# 基于halcon的视觉工作流-章54-N点标定
开发语言·图像处理·算法·计算机视觉·c#