user2410644
user2410644

Reputation: 3891

Get specific pixel from 1D pixel array

I've got a pixel array, containing multiple colors.

int w = 32;
int h = 32;
int[] pixels = new int[w*h];

As You can see, the image in this example has the dimensions 32x32. All pixels are stored in the one dimensional array.

Now for example I would like to have the pixel from the coordinates (5/0), that means the fifth element in the first row of the image. Now the problem is that I've got an one dimensional pixel array. Otherwise I just could've called

int target = pixels[5][0];

How can I achieve getting this specific pixel from the one dimensional array?

Upvotes: 0

Views: 2114

Answers (2)

Deepanshu J bedi
Deepanshu J bedi

Reputation: 1540

It isn't size W*H because they're probably not storing the data quite like you think. Usually, data of this nature is stored such that the first row of the data is stored in the first W entries, the second in the second W, etc.; this results in an array of size W*H. Thus, to get information about something in row X, column Y, you have to get the element at index (W * X) + Y

public int getPixel(x,y) {

   return pixels(y + W*X);
}

Upvotes: 1

radai
radai

Reputation: 24202

like so:

public int getPixel(x,y) {
   //W is your width (number of pixels in a row) == 32
   return pixels(x + W*y);
}

this assumes pixel data is stored in a sequence row-by-row, so you "skip" to the correct row (which is "height" x (number of pixels per row) ) and then add the column

Upvotes: 3

Related Questions