c# - 您可以将位图图像中的一种颜色更改为另一种颜色吗?

标签 c# colors bitmap

对于Bitmap,有一个MakeTransparent方法,有没有类似的方法可以将一种颜色更改为另一种颜色?

// This sets Color.White to transparent
Bitmap myBitmap = new Bitmap(sr.Stream);
myBitmap.MakeTransparent(System.Drawing.Color.White);

有没有什么东西可以做这样的事情?

Bitmap myBitmap = new Bitmap(sr.Stream);
myBitmap.ChangeColor(System.Drawing.Color.Black, System.Drawing.Color.Gray);

最佳答案

出于对 Yorye Nathan 评论的好奇,这是我通过修改 http://msdn.microsoft.com/en-GB/library/ms229672(v=vs.90).aspx 创建的扩展。 .

它可以将位图中的所有像素从一种颜色变为另一种颜色。

public static class BitmapExt
{
    public static void ChangeColour(this Bitmap bmp, byte inColourR, byte inColourG, byte inColourB, byte outColourR, byte outColourG, byte outColourB)
    {
        // Specify a pixel format.
        PixelFormat pxf = PixelFormat.Format24bppRgb;

        // Lock the bitmap's bits.
        Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
        BitmapData bmpData =
        bmp.LockBits(rect, ImageLockMode.ReadWrite,
                     pxf);

        // Get the address of the first line.
        IntPtr ptr = bmpData.Scan0;

        // Declare an array to hold the bytes of the bitmap. 
        // int numBytes = bmp.Width * bmp.Height * 3; 
        int numBytes = bmpData.Stride * bmp.Height;
        byte[] rgbValues = new byte[numBytes];

        // Copy the RGB values into the array.
        Marshal.Copy(ptr, rgbValues, 0, numBytes);

        // Manipulate the bitmap
        for (int counter = 0; counter < rgbValues.Length; counter += 3)
        {
            if (rgbValues[counter] == inColourR &&
                rgbValues[counter + 1] == inColourG &&
                rgbValues[counter + 2] == inColourB)

             {
                rgbValues[counter] = outColourR;
                rgbValues[counter + 1] = outColourG;
                rgbValues[counter + 2] = outColourB;
             }
        }

        // Copy the RGB values back to the bitmap
        Marshal.Copy(rgbValues, 0, ptr, numBytes);

        // Unlock the bits.
        bmp.UnlockBits(bmpData);
    }
}

bmp.ChangeColour(0,128,0,0,0,0); 调用

关于c# - 您可以将位图图像中的一种颜色更改为另一种颜色吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16346212/

相关文章:

c# - .Net Core (2.1) - Lambda 函数可以工作,而在 2.2 中却不行?

javascript - 色彩展示网站开发

java - 如果一个像素的颜色与另一个颜色相似,如何比较

c++ - 如何在 Windows API 中更新用户创建的位图

android - BitmapFactory 从可绘制对象和文件返回位图的不同大小

c# - ECDiffieHellman - mbedTLS 与 C#

c# - 在 WPF 应用程序中按下 Return 时如何模拟 Tab 键按下?

c# - 为什么单例不能直接实现 IObjectReference?

java - 非黑色背景的吴氏抗锯齿线算法

android - 有效地将位图数组转换为视频