Это рабочий пример, вы также можете увидеть его на моем github.
Спасибо Томасу, который поддержал использование getAlphaRaster ()
// get RGB from image
BufferedImage buffImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
try {
buffImage = ImageIO.read(imageFile);
} catch (IOException e) {
}
int imageHeight = buffImage.getHeight();
int imageWidth = buffImage.getWidth();
Color individualPixel = null;
Color tempPixel = null;
BufferedImage buffRed = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB);
BufferedImage buffGreen = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB);
BufferedImage buffBlue = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB);
WritableRaster imageRaster = buffImage.getAlphaRaster();
int[] pixel = new int[4];
int alpha = 0;
for (int i = 0; i < imageHeight; i++) {
for (int j = 0; j < imageWidth; j++) {
individualPixel = new Color(buffImage.getRGB(j, i));
imageRaster.getPixel(j, i, pixel);
alpha = pixel[0];//return 0 for empty
//if(individualPixel.getAlpha() <255 || alpha >0)
System.out.println(j + "," + i + " : " + individualPixel.getAlpha()+ "-"+alpha+ " =>" +
pixel[0] + " " + pixel[1] + " " + pixel[2] + " " + pixel[3]);
//TODO find a way to detect a empty pixel an keep perfect black
if(individualPixel.getRed() == 0
&& individualPixel.getGreen() == 0
&& individualPixel.getBlue() ==0
& alpha == 0) {
//set pixel at location to empty
buffRed.setRGB(j, i, getIntFromColor(0, 0, 0, 0));
buffGreen.setRGB(j, i, getIntFromColor(0, 0, 0, 0));
buffBlue.setRGB(j, i, getIntFromColor(0, 0, 0, 0));
}else {
// RED
tempPixel = new Color(individualPixel.getRed(), 0, 0, individualPixel.getAlpha());
buffRed.setRGB(j, i, getIntFromColor(tempPixel.getRed(), 0, 0, tempPixel.getAlpha()));
// GREEN
tempPixel = new Color(0, individualPixel.getGreen(), 0, individualPixel.getAlpha());
buffGreen.setRGB(j, i, getIntFromColor(0, tempPixel.getGreen(), 0, tempPixel.getAlpha()));
// BLUE
tempPixel = new Color(0, 0, individualPixel.getBlue(), individualPixel.getAlpha());
buffBlue.setRGB(j, i, getIntFromColor(0, 0, tempPixel.getBlue(), tempPixel.getAlpha()));
}
}
System.out.println("");
}
// Save Images to path of selected file
try {
ImageIO.write(buffRed, "png", redImg);
ImageIO.write(buffGreen, "png", greenImg);
ImageIO.write(buffBlue, "png", blueImg);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Failed to create RGB files");
e.printStackTrace();
}