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图像路径");
        }
    }
}
相关推荐
wearegogog1234 分钟前
基于C#的FTP客户端实现方案
java·网络·c#
wuguan_22 分钟前
C#之ArrayList
c#·arraylist
CreasyChan31 分钟前
C# 异步编程详解
开发语言·windows·c#
正运动技术1 小时前
全国产强实时运动控制内核(十二):实时在线变速实现多段速的软着陆
嵌入式硬件·c#·运动控制·运动控制器·运动控制卡·正运动·pc上位机
m5655bj1 小时前
使用 C# 设置 Word 段落对齐样式
开发语言·c#·word
天天进步20151 小时前
依赖注入的艺术:Composer 与模块化设计—— QuantConnect/Lean 源码分析系列一
c#
用户4488466710602 小时前
.NET进阶——深入理解线程(1)同步异步与单线程多线程的区分
c#·.net
编程乐趣2 小时前
qdrant-dotnet:官方提供的开源 .NET 客户端库,用于与 Qdrant 向量搜索引擎操作!
c#·.net
SmoothSailingT2 小时前
C#——单例模式
开发语言·单例模式·c#
Lv11770082 小时前
Visual Studio 中的字符串
ide·笔记·c#·visual studio