Crop image to smallest size by removing transparent pixels in java

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

    This code works for me. The algorithm is simple, it iterates from left/top/right/bottom of the picture and finds the very first pixel in the column/row which is not transparent. It then remembers the new corner of the trimmed picture and finally it returns the sub image of the original image.

    There are things which could be improved.

    1. The algorithm expects, there is the alpha byte in the data. It will fail on an index out of array exception if there is not.

    2. The algorithm expects, there is at least one non-transparent pixel in the picture. It will fail if the picture is completely transparent.

      private static BufferedImage trimImage(BufferedImage img) {
      final byte[] pixels = ((DataBufferByte) img.getRaster().getDataBuffer()).getData();
      int width = img.getWidth();
      int height = img.getHeight();
      int x0, y0, x1, y1;                      // the new corners of the trimmed image
      int i, j;                                // i - horizontal iterator; j - vertical iterator
      leftLoop:
      for (i = 0; i < width; i++) {
          for (j = 0; j < height; j++) {
              if (pixels[(j*width+i)*4] != 0) { // alpha is the very first byte and then every fourth one
                  break leftLoop;
              }
          }
      }
      x0 = i;
      topLoop:
      for (j = 0; j < height; j++) {
          for (i = 0; i < width; i++) {
              if (pixels[(j*width+i)*4] != 0) {
                  break topLoop;
              }
          }
      }
      y0 = j;
      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;
      bottomLoop:
      for (j = height-1; j >= 0; j--) {
          for (i = 0; i < width; i++) {
              if (pixels[(j*width+i)*4] != 0) {
                  break bottomLoop;
              }
          }
      }
      y1 = j+1;
      return img.getSubimage(x0, y0, x1-x0, y1-y0);
      

      }

提交回复
热议问题