Get color of each pixel of an image using BufferedImages

后端 未结 6 1379
南方客
南方客 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条回答
  •  余生分开走
    2020-11-29 07:17

    The problem (also with the answer that was linked from the first answer) is that you hardly ever know what exact type your buffered image will be after reading it with ImageIO. It could contain a DataBufferByte or a DataBufferInt. You may deduce it in some cases via BufferedImage#getType(), but in the worst case, it has type TYPE_CUSTOM, and then you can only fall back to some instanceof tests.

    However, you can convert your image into a BufferedImage that is guaranteed to have a DataBufferInt with ARGB values - namely with something like

    public static BufferedImage convertToARGB(BufferedImage image)
    {
        BufferedImage newImage = new BufferedImage(
            image.getWidth(), image.getHeight(),
            BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = newImage.createGraphics();
        g.drawImage(image, 0, 0, null);
        g.dispose();
        return newImage;
    }
    

    Otherwise, you can call image.getRGB(x,y), which may perform the required conversions on the fly.

    BTW: Note that obtaining the data buffer of a BufferedImage may degrade painting performance, because the image can no longer be "managed" and kept in VRAM internally.

提交回复
热议问题