代码之家  ›  专栏  ›  技术社区  ›  Sean Hanley

如何将32位RGBA图像转换为保灰度alpha

  •  0
  • Sean Hanley  · 技术社区  · 15 年前

    我想,在代码和按需,转换一个32位RGBA图像对象(原来是一个32位PNG)到它的32位灰度对应物。

    我已经准备好了 read 几个 other 这里的问题,以及网上的许多文章。我试过用ColorMatrix来做这件事,但它似乎不能很好地处理alpha。完全不透明的像素完全可以进行灰度调整。任何部分透明的像素似乎都不能很好地转换,因为这些像素中仍然有颜色的色调。这足以引起注意。

    new System.Drawing.Imaging.ColorMatrix(new float[][]{
                        new float[] {0.299f, 0.299f, 0.299f, 0, 0},
                        new float[] {0.587f, 0.587f, 0.587f, 0, 0},
                        new float[] {0.114f, 0.114f, 0.114f, 0, 0},
                        new float[] {     0,      0,      0, 1, 0},
                        new float[] {     0,      0,      0, 0, 1}
                        });
    

    正如我所读到的,这是一个非常标准的NTSC加权矩阵。然后我用它,连同 Graphics.DrawImage ,但正如我所说的,部分透明的像素仍然是彩色的。我应该指出这是通过WinForms显示图像对象 PictureBox

    3 回复  |  直到 8 年前
        1
  •  5
  •   Dan Byström    15 年前

    你有没有可能用彩色矩阵把图像画到自己身上?当然,这是行不通的(因为如果你在绿色像素上画一些半透明的灰色,一些绿色就会发光)。您需要将其绘制到一个新的空位图上,该位图只包含透明像素。

        2
  •  4
  •   Sean Hanley    6 年前

    感谢 danbystrom 出于好奇,我的确在原作的基础上重新画了一遍。对于任何感兴趣的人,以下是我使用的正确方法:

    using System.Drawing;
    using System.Drawing.Imaging;
    
    public Image ConvertToGrayscale(Image image)
    {
        Image grayscaleImage = new Bitmap(image.Width, image.Height, image.PixelFormat);
    
        // Create the ImageAttributes object and apply the ColorMatrix
        ImageAttributes attributes = new System.Drawing.Imaging.ImageAttributes();
        ColorMatrix grayscaleMatrix = new ColorMatrix(new float[][]{
            new float[] {0.299f, 0.299f, 0.299f, 0, 0},
            new float[] {0.587f, 0.587f, 0.587f, 0, 0},
            new float[] {0.114f, 0.114f, 0.114f, 0, 0},
            new float[] {     0,      0,      0, 1, 0},
            new float[] {     0,      0,      0, 0, 1}
            });
        attributes.SetColorMatrix(grayscaleMatrix);
    
        // Use a new Graphics object from the new image.
        using (Graphics g = Graphics.FromImage(grayscaleImage))
        {
            // Draw the original image using the ImageAttributes created above.
            g.DrawImage(image,
                        new Rectangle(0, 0, grayscaleImage.Width, grayscaleImage.Height),
                        0, 0, grayscaleImage.Width, grayscaleImage.Height,
                        GraphicsUnit.Pixel,
                        attributes);
        }
    
        return grayscaleImage;
    }
    
        3
  •  0
  •   thomasfedb    15 年前

    如果您将图像转换为TGA,一种未压缩的imaeg格式,您可以使用“RubyPixels”直接编辑像素数据,做任何您想做的事情。然后可以将其转换回PNG。