views:

116

answers:

2

I have a sprite sheet which has each image centered in a 32x32 cell. The actual images are not 32x32, but slightly smaller. What I'd like to do is take a cell and crop the transparent pixels so the image is as small as it can be.

How would I do that in Java (JDK 6)?

Here is an example of how I'm currently breaking up the tile sheet into cells:

BufferedImage tilesheet = ImageIO.read(getClass().getResourceAsStream("/sheet.png");
for (int i = 0; i < 15; i++) {
  Image img = tilesheet.getSubimage(i * 32, 0, 32, 32);
  // crop here..
}

My current idea was to test each pixel from the center working my way out to see if it is transparent, but I was wondering if there would be a faster/cleaner way of doing this.

+1  A: 

I think this is exactly what you should do, loop through the array of pixels, check for alpha and then discard. Although when you for example would have a star shape it will not resize the image to be smaller be aware of this.

Yonathan Klijnsma
Yes I'm aware of something like a star, not resizing much. I was hoping there was some kind of built in filter.
Ruggs
A: 

If your sheet already has transparent pixels, the BufferedImage returned by getSubimage() will, too. The default Graphics2D composite rule is AlphaComposite.SRC_OVER, which should suffice for drawImage().

If the sub-images have a distinct background color, use a LookupOp with a four-component LookupTable that sets the alpha component to zero for colors that match the background.

I'd traverse the pixel raster only as a last resort.

Addendum: Extra transparent pixels may interfere with collision detection, etc. Cropping them will require working with a WritableRaster directly. Rather than working from the center out, I'd start with the borders, using a pair of getPixels()/setPixels() methods that can modify a row or column at a time. If a whole row or column has zero alpha, mark it for elimination when you later get a sub-image.

trashgod
I'm not having trouble setting the transparent pixels, like you said subimage is already doing that. What I want to do is to clip/crop the image as to trim as much of the surrounding transparent pixels as possible. My cells are 32x32, however a lot of times the image i'm interested in is only something like 14x28.
Ruggs