0

What order does PixelGrabber put pixels into the array in java? Does it take the pixels along the width of the image first? Or along the height of the image first?

public static int[] convertImgToPixels(Image img, int width, int height) {
    int[] pixel = new int[width * height]; 
    PixelGrabber pixels = new PixelGrabber(img, 0, 0, width, height, pixel, 0, width); 
    try { 
        pixels.grabPixels(); 
    } catch (InterruptedException e) { 
        throw new IllegalStateException("Interrupted Waiting for Pixels"); 
    } 
    if ((pixels.getStatus() & ImageObserver.ABORT) != 0) { 
        throw new IllegalStateException("Image Fetch Aborted"); 
    } 
    return pixel; 
}
Obicere
  • 2,999
  • 3
  • 20
  • 31
Kat42912
  • 41
  • 1
  • 6
  • This is the code I've got so far: public static int[] convertImgToPixels(Image img, int width, int height) { int[] pixel = new int[width * height]; PixelGrabber pixels = new PixelGrabber(img, 0, 0, width, height, pixel, 0, width); try { pixels.grabPixels(); } catch (InterruptedException e) { throw new IllegalStateException("Interrupted Waiting for Pixels"); } if ((pixels.getStatus() & ImageObserver.ABORT) != 0) { throw new IllegalStateException("Image Fetch Aborted"); } return pixel; } – Kat42912 Mar 31 '15 at 02:58
  • I'm trying to take the pixels out of an image and out them into an array – Kat42912 Mar 31 '15 at 03:06

2 Answers2

0

I'm pretty sure it uses row major order, but the easiest way is to actually grab the pixels, set a sequence of them to a particular color (for easy identification) and then save them out to an image. If the pixel strip appears vertical than the order is column major, otherwise it is row major. You can use code like: here

public static Image getImageFromArray(int[] pixels, int width, int height) {
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        WritableRaster raster = (WritableRaster) image.getData();
        raster.setPixels(0,0,width,height,pixels);
        return image;
    }

To convert an the int[] to an image.

Also, I use ((DataBufferInt)img.grtRaster().getDataBuffer()).getData() to quickly grab the pixels of the image. Any modifications to that int[] will reflect in the image and vice versa. And that is row major for sure.

Community
  • 1
  • 1
TameHog
  • 950
  • 11
  • 23
0

In the code example provided by the documentation

It has the following for loops:

for (int j = 0; j < h; j++) {
    for (int i = 0; i < w; i++) {
        handlesinglepixel(x+i, y+j, pixels[j * w + i]);
    }
}

The access pixels[j * w + i] shows that it goes first along the row, then by along the columns. It grabs the pixels along the width first.

Obicere
  • 2,999
  • 3
  • 20
  • 31