code: public static int getNumDirectories(RandomAccessFileOrArray stream)
      throws IOException{
          long pointer = stream.getFilePointer(); // Save stream pointer
          
          stream.seek(0L);
          int endian = stream.readUnsignedShort();
          if (!isValidEndianTag(endian)) {
              throw new
              IllegalArgumentException("Bad endianness tag (not 0x4949 or 0x4d4d).");
          }
          boolean isBigEndian = (endian == 0x4d4d);
          int magic = readUnsignedShort(stream, isBigEndian);
          if (magic != 42) {
              throw new
              IllegalArgumentException("Bad magic number, should be 42.");
          }
          
          stream.seek(4L);
          long offset = readUnsignedInt(stream, isBigEndian);
          
          int numDirectories = 0;
          while (offset != 0L) {
              ++numDirectories;
              
              // EOFException means IFD was probably not properly terminated.
              try {
                  stream.seek(offset);
                  int entries = readUnsignedShort(stream, isBigEndian);
                  stream.skip(12*entries);
                  offset = readUnsignedInt(stream, isBigEndian);
              } catch(EOFException eof) {
                  //numDirectories--;
                  break;
              }
          }
          
          stream.seek(pointer); // Reset stream pointer
          return numDirectories;
      }
docs: Returns the number of image directories (subimages) stored in a
  given TIFF file, represented by a <code>SeekableStream</code>.