I am trying to make a function that will crop the transparent edges of a BufferedImage
only from the right and left side.
So, I found this method of doing this somewhere online, however I don't really understand what is the pixels[]
array filled with? I assumed it was the alpha, red, green, blue values for every single pixel (judging by the 4
in (j*width+i)*4
, it picks every fourth element), but the length of this array is 299208
for a 68x67
image (I know it's not a power of 2, just ignore that).
So, how do I accomplish this and I'm curious what's actually stored in this pixel array?
public static BufferedImage trimHorizontally(BufferedImage img) {
final byte[] pixels = ((DataBufferByte)img.getRaster().getDataBuffer()).getData();
int width = img.getWidth(), height = img.getHeight();
int x0, x1;
int j, i;
leftLoop:
for(i = 0; i < width; i++) {
for(j = 0; j < height; j++) {
if(pixels[(j*width+i)*4] != 0) {
break leftLoop;
}
}
}
x0 = i;
rightLoop:
for(i = width-1; i >= 0; i--) {
for(j = 0; j < height; j++) {
if(pixels[(j*width+i)*4] != 0) {
break rightLoop;
}
}
}
x1 = i+1;
return img.getSubimage(x0, 0, x1-x0, height);
}
What I'm basically doing in the above code is scanning the image from the left and from the right side, checking for the alpha value and marking the distance I need to crop, but it throws an exception because the loops finish without detecting any opaque pixels (and the images I'm cropping are not transparent for sure).
I made a check and found out that the alpha values greater than 0
are actually above the index of 35000
of the pixels[]
array, and with the (j*width+i)*4
calculation I can only reach 18000
....