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图像路径");
        }
    }
}
相关推荐
19H13 分钟前
Flink-Source算子状态恢复分析
c#·linq
枯萎穿心攻击2 小时前
响应式编程入门教程第二节:构建 ObservableProperty<T> — 封装 ReactiveProperty 的高级用法
开发语言·unity·c#·游戏引擎
Eiceblue4 小时前
【免费.NET方案】CSV到PDF与DataTable的快速转换
开发语言·pdf·c#·.net
昏睡红猹11 小时前
C#脚本化(Roslyn):如何在运行时引入nuget包
c#
张人玉12 小时前
C# 常量与变量
java·算法·c#
就是有点傻13 小时前
在C#中,可以不实例化一个类而直接调用其静态字段
c#
软件黑马王子13 小时前
C#系统学习第八章——字符串
开发语言·学习·c#
阿蒙Amon13 小时前
C#读写文件:多种方式详解
开发语言·数据库·c#
就是有点傻14 小时前
C#如何实现中英文快速切换
数据库·c#
一名用户18 小时前
unity实现梦日记式传送组件
后端·c#·unity3d