code: public static void computeTrimmedBounds (BufferedImage image, Rectangle tbounds)
      {
          // this could be more efficient, but it's run as a batch process and doesn't really take
          // that long anyway
          int width = image.getWidth(), height = image.getHeight();
  
          int firstrow = -1, lastrow = -1, minx = width, maxx = 0;
          for (int yy = 0; yy < height; yy++) {
  
              int firstidx = -1, lastidx = -1;
              for (int xx = 0; xx < width; xx++) {
                  // if this pixel is transparent, do nothing
                  int argb = image.getRGB(xx, yy);
                  if ((argb >> 24) == 0) {
                      continue;
                  }
  
                  // otherwise, if we've not seen a non-transparent pixel, make a note that this is
                  // the first non-transparent pixel in the row
                  if (firstidx == -1) {
                      firstidx = xx;
                  }
                  // keep track of the last non-transparent pixel we saw
                  lastidx = xx;
              }
  
              // if we saw no pixels on this row, we can bail now
              if (firstidx == -1) {
                  continue;
              }
  
              // update our min and maxx
              minx = Math.min(firstidx, minx);
              maxx = Math.max(lastidx, maxx);
  
              // otherwise keep track of the first row on which we see pixels and the last row on
              // which we see pixels
              if (firstrow == -1) {
                  firstrow = yy;
              }
              lastrow = yy;
          }
  
          // fill in the dimensions
          if (firstrow != -1) {
              tbounds.x = minx;
              tbounds.y = firstrow;
              tbounds.width = maxx - minx + 1;
              tbounds.height = lastrow - firstrow + 1;
          } else {
              // Entirely blank image.  Return 1x1 blank image.
              tbounds.x = 0;
              tbounds.y = 0;
              tbounds.width = 1;
              tbounds.height = 1;
          }
      }
docs: Computes the bounds of the smallest rectangle that contains all non-transparent pixels of
  this image. This isn't extremely efficient, so you shouldn't be doing this anywhere
  exciting.