private void build(ImageSegment segment) throws IOException {
    SortedSet<ImageSegment> set = segments.get(segment.getId());
    if (set == null) {
      set = new TreeSet<>();
      segments.put(segment.getId(), set);
    }

    set.add(segment);
    segment = set.last();
    if (segment.isLast() && set.size() > segment.getIndex()) {
      segments.remove(segment.getId());
      build(set);
    }
  }
  private void breakDown(final ImageData img) throws IOException {

    try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {

      ImageIO.write(img.getImage(), "png", bos);
      final byte[] image = bos.toByteArray();

      ImageSegment prev = null;
      for (int i = 0; i < image.length; i += BUFFER_SIZE) {

        final byte[] buffer = new byte[BUFFER_SIZE];
        final int num = Math.min(BUFFER_SIZE, image.length - i);
        for (int j = 0; j < num; ++j) {
          buffer[j] = image[i + j];
        }

        int index = 0;
        if (prev != null) {
          index = prev.getIndex() + 1;
          sendData(prev);
        }
        prev = new ImageSegment(img.getTimestamp(), id, index, buffer, num, false);
      }
      if (prev != null) {
        sendData(
            new ImageSegment(
                prev.getTimestamp(),
                prev.getId(),
                prev.getIndex(),
                prev.getData(),
                prev.getNum(),
                true));
      }

      id += 1;
    }
  }