Crop image to smallest size by removing transparent pixels in java

后端 未结 6 969
走了就别回头了
走了就别回头了 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:36

    A simple fix for code above. I used the median for RGB and fixed the min() function of x and y:

    private static BufferedImage trim(BufferedImage img) {
        int width = img.getWidth();
        int height = img.getHeight();
    
        int top = height / 2;
        int bottom = top;
    
        int left = width / 2 ;
        int right = left;
    
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                if (isFg(img.getRGB(x, y))){
    
                    top    = Math.min(top, y);
                    bottom = Math.max(bottom, y);
    
                    left   = Math.min(left, x);
                    right  = Math.max(right, x);
    
                }
            }
        }
    
        return img.getSubimage(left, top, right - left, bottom - top);
    }
    
    private static boolean isFg(int v) {
        Color c = new Color(v);
        return(isColor((c.getRed() + c.getGreen() + c.getBlue())/2));
    }
    
    private static boolean isColor(int c) {
        return c > 0 && c < 255;
    }
    

提交回复
热议问题