Get color of each pixel of an image using BufferedImages

后端 未结 6 1371
南方客
南方客 2020-11-29 06:49

I am trying to get every single color of every single pixel of an image. My idea was following:

int[] pixels;
BufferedImage image;

image = ImageIO.read(this         


        
6条回答
  •  猫巷女王i
    2020-11-29 07:24

    import javax.imageio.ImageIO;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    
    public class Main {
        public static void main(String[] args) throws IOException {
            BufferedImage bufferedImage = ImageIO.read(new File("norris.jpg"));
            int height = bufferedImage.getHeight(), width = bufferedImage.getWidth();
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    int RGBA = bufferedImage.getRGB(x, y);
                    int alpha = (RGBA >> 24) & 255;
                    int red = (RGBA >> 16) & 255;
                    int green = (RGBA >> 8) & 255;
                    int blue = RGBA & 255;
                }
            }
        }
    }
    

    Assume the buffered image represents an image with 8-bit RGBA color components packed into integer pixels, I search for "RGBA color space" on wikipedia and found following:

    In the byte-order scheme, "RGBA" is understood to mean a byte R, followed by a byte G, followed by a byte B, and followed by a byte A. This scheme is commonly used for describing file formats or network protocols, which are both byte-oriented.

    With simple Bitwise and Bitshift you can get the value of each color and the alpha value of the pixel.

    Very interesting is also the other order scheme of RGBA:

    In the word-order scheme, "RGBA" is understood to represent a complete 32-bit word, where R is more significant than G, which is more significant than B, which is more significant than A. This scheme can be used to describe the memory layout on a particular system. Its meaning varies depending on the endianness of the system.

提交回复
热议问题