John
John

Reputation: 816

Java BufferedImage to pixel array

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).

Upvotes: 0

Views: 2564

Answers (1)

chris
chris

Reputation: 1785

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.

Upvotes: 1

Related Questions