how can I convert an image to grayscale without losing transparency?

前端 未结 4 2035
小鲜肉
小鲜肉 2021-01-14 07:55

I am having problems converting a colored image with some transparent pixels to grayscale. I have searched and found related questions on this website but nothing I have be

4条回答
  •  有刺的猬
    2021-01-14 08:28

    Important: You should probably use @MadProgrammers solution (ColorConvertOp) if proper gray scale conversion is what you want. I voted for that. :-)

    This answer is more for completeness:

    If you really want a BufferedImage that has CS_GRAY color space and transparency, it's possible to create a custom (will result in TYPE_CUSTOM) BufferedImage. The code below will make something like a "TYPE_2BYTE_GRAY_ALPHA" type (8 bits per sample, 2 samples per pixel). It will use half the memory of a TYPE_INT_ARGB or TYPE_4BYTE_ABGR image, but it will most likely lose hardware acceleration, and possibly miss some optimized loops in the Java2D drawing pipelines (that said, my testing shows fully acceptable performance on OS X).

    /** Color Model usesd for raw GRAY + ALPHA */
    private static final ColorModel CM_GRAY_ALPHA =
            new ComponentColorModel(
                    ColorSpace.getInstance(ColorSpace.CS_GRAY),
                    true, false, Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE
            );
    
    public static BufferedImage create2ByteGrayAlphaImage(int width, int height) {
        int[] bandOffsets = new int[] {1, 0}; // gray + alpha
        int bands = bandOffsets.length; // 2, that is
    
        // Init data buffer of type byte
        DataBuffer buffer = new DataBufferByte(width * height * bands);
    
        // Wrap the data buffer in a raster
        WritableRaster raster =
                Raster.createInterleavedRaster(buffer, width, height,
                        width * bands, bands, bandOffsets, new Point(0, 0));
    
        // Create a custom BufferedImage with the raster and a suitable color model
        return new BufferedImage(CM_GRAY_ALPHA, raster, false, null);
    }
    

提交回复
热议问题