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图像路径");
        }
    }
}
相关推荐
ISDF-工软未来2 小时前
C# 泛型简单案例
c#
疯狂的维修5 小时前
C#中一段程序类比博图
c#
时光追逐者6 小时前
C#/.NET/.NET Core技术前沿周刊 | 第 53 期(2025年9.1-9.7)
c#·.net·.netcore
冷冷的菜哥6 小时前
ASP.NET Core使用MailKit发送邮件
后端·c#·asp.net·发送邮件·mailkit
weixin_447103587 小时前
C#之LINQ
c#·linq
ysn111117 小时前
反编译分析C#闭包
c#
one99610 小时前
WPF应用程序中的异常处理
c#·.net·wpf
almighty2710 小时前
C# ObjectListView实现树状文件夹浏览
c#·树状图·objectlistview·c#树状图·文件显示
ccut 第一混17 小时前
c# 调用basler 相机
c#·halcon·basler
TomCode先生17 小时前
c#动态树形表达式详解
开发语言·c#