Crop image to smallest size by removing transparent pixels in java

后端 未结 6 963
走了就别回头了
走了就别回头了 2021-01-21 15:04

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 tr

6条回答
  •  无人及你
    2021-01-21 15:59

    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.

提交回复
热议问题