且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Java中将图像转换为灰度的错误亮度

更新时间:2023-01-23 10:28:47

最后我写了 GrayscaleFilter 类实现 BufferedImageOp 界面。

Finally I've wrote GrayscaleFilter class implementing BufferedImageOp interface.

我跟着这个非常好的指南。

这是相关的代码片段:

public class GrayscaleFilter extends AbstractFilter
{
    public final static double[] METHOD_AVERAGE = {1.0/3.0, 1.0/3.0, 1.0/3.0};
    public final static double[] METHOD_GIMP_LUMINOSITY = {0.21, 0.71, 0.07};

    public GrayscaleFilter(final double[] rgb)
    {
        this(rgb[0], rgb[1], rgb[2]);
    }

    public BufferedImage filter(BufferedImage src, BufferedImage dest)
    {
        if (src.getType() == BufferedImage.TYPE_BYTE_GRAY)
        {
            dest = src;
            return dest;
        }

        if (dest == null)
            dest = createCompatibleDestImage(src, null);

        final int width = src.getWidth();
        final int height = src.getHeight();

        int[] inPixels = new int[width * height];
        GraphicsUtilities.getPixels(src, 0, 0, width, height, inPixels);
        byte[] outPixels = doFilter(inPixels);
        GraphicsUtilities.setPixels(dest, 0, 0, width, height, outPixels);
        return dest;
    }

    private byte[] doFilter(int[] inputPixels)
    {
        int red, green, blue;
        int i = 0;
        byte[] outPixels = new byte[inputPixels.length];

        for(int pixel : inputPixels)
        {
            // Obtengo valores originales
            red   = (pixel >> 16) & 0xFF;
            green = (pixel >> 8) & 0xFF;
            blue  = pixel & 0xFF;

            // Calculo valores nuevos
            outPixels[i++] = (byte)(
                 red   * red_part   +
                 green * green_part +
                 blue  * blue_part
            );
        }
        return outPixels;
    }

    public BufferedImage createCompatibleDestImage(BufferedImage src, ColorModel destCM)
    {
        return new BufferedImage(src.getWidth(), src.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
    }
}