C# RGB图像转为灰度图像、灰度图像转为RGB图像

RGB图像转为灰度图像

cs 复制代码
using System;
using System.Drawing;
using System.Drawing.Imaging;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // 创建RGB图像
            Image img = new Bitmap("RGB图像路径");
            // 获取RGB图像的Width和Height
            int width = img.Width;
            int height = img.Height;
            // 创建灰度图像
            Image grayImg = new Bitmap(width, height);
            // 获取灰度图像的BytesPerPixel
            int grayBytesPerPixel = grayImg.GetPixelFormatSize(Color.Format32bppArgb);
            // 计算灰度图像的总像素数
            int grayPixelCount = width * height;
            // 遍历RGB图像的每个像素,将其转为灰度值并写入灰度图像
            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    Color c = img.GetPixel(x, y);
                    int r = (int)(c.R / 255 * 255);
                    int g = (int)(c.G / 255 * 255);
                    int b = (int)(c.B / 255 * 255);
                    int gray = (r + g + b) / 3;
                    grayImg.SetPixel(x, y, Color.FromArgb(gray));
                }
            }
            // 显示灰度图像
            grayImg.Save("灰度图像路径");
        }
    }
}

灰度图像转为RGB图像

cs 复制代码
using System;
using System.Drawing;
using System.Drawing.Imaging;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // 创建灰度图像
            Image img = new Bitmap("灰度图像路径");
            // 获取灰度图像的Width和Height
            int width = img.Width;
            int height = img.Height;
            // 创建RGB图像
            Image rgbImg = new Bitmap(width, height);
            // 获取RGB图像的BytesPerPixel
            int rgbBytesPerPixel = rgbImg.GetPixelFormatSize(Color.Format32bppArgb);
            // 计算RGB图像的总像素数
            int rgbPixelCount = width * height;
            // 遍历灰度图像的每个像素,将其转为RGB值并写入RGB图像
            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    Color c = img.GetPixel(x, y);
                    int gray = c.R;
                    rgbImg.SetPixel(x, y, Color.FromArgb(gray, gray, gray));
                }
            }
            // 显示RGB图像
            rgbImg.Save("RGB图像路径");
        }
    }
}
相关推荐
2501_930707781 小时前
使用C#代码在 PowerPoint 中组合或取消组合形状
开发语言·c#
baivfhpwxf20239 小时前
c# 中对像之间频繁的转换会慢吗?
开发语言·c#
加号311 小时前
【C#】 实现 XRC 异或冗余校验:原理与实践
c#·xrc
小钻风336611 小时前
Java + Spring Boot 操作 Kafka 完整学习指南
c#·linq
叫我少年11 小时前
C# 程序的常规结构 — 命名空间、类型、入口点与表达式
c#
步步为营DotNet16 小时前
探秘.NET 11:C# 14 特性在后端性能优化中的深度应用
性能优化·c#·.net
Chris _data16 小时前
C# 与 PLC Modbus RTU 通信实践:从单例到线程安全的连接监控
开发语言·安全·c#
Chris _data17 小时前
C# WinForms 后台轮询 Modbus 数据与 UI 更新实践
开发语言·ui·c#
魔法阵维护师17 小时前
从零开发游戏需要学习的c#模块,第二十四章(场景管理 —— 标题、游戏、结束画面)
学习·游戏·c#
唐青枫17 小时前
别把登录写散了:C#.NET IdentityServer4 统一认证与 JWT 授权实战
c#·.net