• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

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

武飞扬头像
wangnaisheng
帮助8

RGB图像转为灰度图像

  1.  
    using System;
  2.  
    using System.Drawing;
  3.  
    using System.Drawing.Imaging;
  4.  
     
  5.  
    namespace ConsoleApp
  6.  
    {
  7.  
    class Program
  8.  
    {
  9.  
    static void Main(string[] args)
  10.  
    {
  11.  
    // 创建RGB图像
  12.  
    Image img = new Bitmap("RGB图像路径");
  13.  
    // 获取RGB图像的Width和Height
  14.  
    int width = img.Width;
  15.  
    int height = img.Height;
  16.  
    // 创建灰度图像
  17.  
    Image grayImg = new Bitmap(width, height);
  18.  
    // 获取灰度图像的BytesPerPixel
  19.  
    int grayBytesPerPixel = grayImg.GetPixelFormatSize(Color.Format32bppArgb);
  20.  
    // 计算灰度图像的总像素数
  21.  
    int grayPixelCount = width * height;
  22.  
    // 遍历RGB图像的每个像素,将其转为灰度值并写入灰度图像
  23.  
    for (int y = 0; y < height; y )
  24.  
    {
  25.  
    for (int x = 0; x < width; x )
  26.  
    {
  27.  
    Color c = img.GetPixel(x, y);
  28.  
    int r = (int)(c.R / 255 * 255);
  29.  
    int g = (int)(c.G / 255 * 255);
  30.  
    int b = (int)(c.B / 255 * 255);
  31.  
    int gray = (r g b) / 3;
  32.  
    grayImg.SetPixel(x, y, Color.FromArgb(gray));
  33.  
    }
  34.  
    }
  35.  
    // 显示灰度图像
  36.  
    grayImg.Save("灰度图像路径");
  37.  
    }
  38.  
    }
  39.  
    }
学新通

灰度图像转为RGB图像

  1.  
    using System;
  2.  
    using System.Drawing;
  3.  
    using System.Drawing.Imaging;
  4.  
     
  5.  
    namespace ConsoleApp
  6.  
    {
  7.  
    class Program
  8.  
    {
  9.  
    static void Main(string[] args)
  10.  
    {
  11.  
    // 创建灰度图像
  12.  
    Image img = new Bitmap("灰度图像路径");
  13.  
    // 获取灰度图像的Width和Height
  14.  
    int width = img.Width;
  15.  
    int height = img.Height;
  16.  
    // 创建RGB图像
  17.  
    Image rgbImg = new Bitmap(width, height);
  18.  
    // 获取RGB图像的BytesPerPixel
  19.  
    int rgbBytesPerPixel = rgbImg.GetPixelFormatSize(Color.Format32bppArgb);
  20.  
    // 计算RGB图像的总像素数
  21.  
    int rgbPixelCount = width * height;
  22.  
    // 遍历灰度图像的每个像素,将其转为RGB值并写入RGB图像
  23.  
    for (int y = 0; y < height; y )
  24.  
    {
  25.  
    for (int x = 0; x < width; x )
  26.  
    {
  27.  
    Color c = img.GetPixel(x, y);
  28.  
    int gray = c.R;
  29.  
    rgbImg.SetPixel(x, y, Color.FromArgb(gray, gray, gray));
  30.  
    }
  31.  
    }
  32.  
    // 显示RGB图像
  33.  
    rgbImg.Save("RGB图像路径");
  34.  
    }
  35.  
    }
  36.  
    }
学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /news/detail/tanhbceajh
系列文章
更多 icon
同类精品
更多 icon
继续加载