getEnclosingRectangle method

List<int>? getEnclosingRectangle()

This is useful in detecting the enclosing rectangle of a 'pure' barcode.

@return {@code left,top,width,height} enclosing rectangle of all 1 bits, or null if it is all white

Implementation

List<int>? getEnclosingRectangle() {
  int left = _width;
  int top = _height;
  int right = -1;
  int bottom = -1;

  for (int y = 0; y < _height; y++) {
    for (int x32 = 0; x32 < _rowSize; x32++) {
      final theBits = _bits[y * _rowSize + x32];
      if (theBits != 0) {
        if (y < top) {
          top = y;
        }
        if (y > bottom) {
          bottom = y;
        }
        if (x32 * 32 < left) {
          int bit = 0;
          while ((theBits << (31 - bit)).toUnsigned(32) == 0) {
            bit++;
          }
          if ((x32 * 32 + bit) < left) {
            left = x32 * 32 + bit;
          }
        }
        if (x32 * 32 + 31 > right) {
          int bit = 31;
          while ((theBits >>> bit) == 0) {
            bit--;
          }
          if ((x32 * 32 + bit) > right) {
            right = x32 * 32 + bit;
          }
        }
      }
    }
  }

  if (right < left || bottom < top) {
    return null;
  }

  return [left, top, right - left + 1, bottom - top + 1];
}