c# 设置图片透明度

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


        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();
            }
        }

相关推荐

  1. c# 设置图片透明度

    2024-03-27 13:52:02       41 阅读
  2. QT 设置窗口不透明度

    2024-03-27 13:52:02       35 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-27 13:52:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-27 13:52:02       106 阅读
  3. 在Django里面运行非项目文件

    2024-03-27 13:52:02       87 阅读
  4. Python语言-面向对象

    2024-03-27 13:52:02       96 阅读

热门阅读

  1. 【LAMMPS学习】五、LAMMPS命令(1) LAMMPS 输入脚本

    2024-03-27 13:52:02       38 阅读
  2. 数据库(四)

    2024-03-27 13:52:02       37 阅读
  3. Spring和Spring Boot的区别

    2024-03-27 13:52:02       43 阅读
  4. Mysql数据库:索引

    2024-03-27 13:52:02       42 阅读
  5. C++服务内存分析

    2024-03-27 13:52:02       39 阅读
  6. STEVE - Voracious Steve dfs , 以及为什么不能博弈

    2024-03-27 13:52:02       43 阅读
  7. nginx负载均衡模式

    2024-03-27 13:52:02       41 阅读
  8. 能否把 Redis 当做消息队列来用呢?

    2024-03-27 13:52:02       44 阅读
  9. Python的异常处理

    2024-03-27 13:52:02       40 阅读