The SampleModel.getPixel()
(used internally by the Raster.getPixel()
) returns pixel components in the order of bands. While it is possible to create a bogus instance of SampleModel
programmatically with the band order different from the RGB, usually instances of the SampleModel
s are created by some ColorModel
which constructs the SampleModel
with bands in the same order as the order of color components in the ColorModel
.
The order of color model components is documented in the java.awt.image.ColorModel javadoc:
The number, order, and interpretation of color components for a
ColorModel
is specified by itsColorSpace
.
In theory you should check whether the color space is from the RGB family:
public static void processImage( BufferedImage source )
{
ColorSpace colorSpace = source.getColorModel().getColorSpace();
if ( dumpColorSpaceProperties ) {
System.out.printf( "color space type: %d, is RGB = %s%n", colorSpace.getType(), colorSpace.isCS_sRGB() );
for ( int i = 0; i < colorSpace.getNumComponents(); i++ ) {
System.out.printf( "component %d = %s%n", i, colorSpace.getName( i ) );
}
}
if ( colorSpace.getType() == ColorSpace.TYPE_RGB ) {
// guaranteed RGB(A) order, proceed with raster.getPixels()
} else {
// well, find a way to convert from that space into RGB
throw new AssertionError( "color space type = " + colorSpace.getType() );
}
}
In practice it all depends on the source of the image. Images created via BufferedImage(width, height, imageType)
always use RGB space. Images obtained from a file can use some other color space if the image file format supports different color space and if that particular image file uses non-RGB space.
If you know the image source you do not need to check the color space and you can assume the RGB(A) output from the Raster.getPixels()
.
The ColorSpace.getName(int)
source provides insight into default components for most color sets that can be encountered in practice.