0

I saw a thread on converting a BufferedImage to an array of pixels/bytes. Using getRGB directly on the image works, but is not ideal as it is too slow to gather all pixels. I tried the alternate way of simply grabbing the pixel data.

    //convert canvas to bufferedimage
    BufferedImage img = new BufferedImage(500, 500, BufferedImage.TYPE_3BYTE_BGR);
    Graphics2D g2 = img.createGraphics();
    canvas.printAll(g2);
    g2.dispose();

    System.out.println(img.getRGB(0, 0));    //-16777216 works but not ideal

    byte[] pixels = ((DataBufferByte) img.getRaster().getDataBuffer()).getData();
    for(byte b : pixels){
        System.out.println(b);    //all 0 doesnt work
    }

However, the whole byte array seems to be empty (filled with 0s).

1 Answer 1

1

I don't know what canvas means in your code but this works perfectly:

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;

public class Px {

    public static void main(String[] args) {
        new Px().go();
    }

    private void go() {
        BufferedImage img = new BufferedImage(5, 5, BufferedImage.TYPE_3BYTE_BGR);
        Graphics2D g2 = img.createGraphics();
        g2.setColor(Color.red);
        g2.fillRect(0, 0, 2, 2);
        g2.dispose();

        byte[] pixels = ((DataBufferByte) img.getRaster().getDataBuffer()).getData();
        for (byte b : pixels) {
            System.out.print(b + ",");
        }
    }
}

The result is this:

0,0,-1,0,0,-1,0,0,0,0,0,0,0,0,0,0,0,-1,0,0,-1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,

The color order is blue green red. So my red rect appears as bytes in 0,0,-1,0,0,-1 etc. I assume that -1 is 'the same' as 255.

You could explore your line canvas.printAll(). Maybe the canvas only contains black pixels.

Sign up to request clarification or add additional context in comments.

3 Comments

But that leaves the question: why does getRGB work?
byte in java is a signed type. With it's 8 bit you can display numbers from -128 to +127. However image bytes are generally non-signed. So what happens if you turn an unsigned byte 255 = (11111111) to signed? Check en.wikipedia.org/wiki/Two%27s_complement
The getRGB docu tells me that the used model is TYPE_INT_ARGB. Maybe there is a value for the alpha in there. I don't want to dive into that. I tried another function called getPixel. So img.getData().getPixel(...) fills an int array with (in my case of red) 255,0,0. That looks clear to me to be red :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.