Skip to content

Sprite Sheet Packer — Java source

Pack loose sprites into one optimized sheet with atlas JSON and CSS — entirely in your browser. Nothing uploads.

This is the Java implementation — the same logic the interactive tool runs, in a shareable, citable form.

// sprite-sheet-packer — MaxRects best-short-side-fit sheet packer. Java port
// (canonical TS: src/lib/sprite-packer.ts), standard library only: validation,
// biggest-first ordering, sheet growth, MaxRects splitting, power-of-two
// rounding, plus the JSON-atlas and CSS emitters.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

// Package-private: display snippets keep the repo filename (java.java), which
// need not match the class name.
final class SpriteSheetPacker {

  record SpriteSize(String id, int w, int h) {}

  record PackedRect(String id, int x, int y, int w, int h, boolean rotated) {}

  // The final sheet: power-of-two dims plus rects in input order.
  record PackResult(int sheetW, int sheetH, List<PackedRect> rects) {}

  // Mirrors the TS PackOptions.
  record PackOptions(int maxWidth, int maxHeight, boolean allowRotate) {
    PackOptions {
      if (maxWidth <= 0) maxWidth = 4096;
      if (maxHeight <= 0) maxHeight = 4096;
    }
  }

  // The Java twin of the TS PackError class.
  static final class PackError extends RuntimeException {
    final String code; // 'empty' | 'invalid' | 'overflow'

    PackError(String code, String message) {
      super(message);
      this.code = code;
    }
  }

  private record FreeRect(int x, int y, int w, int h) {}

  private static final int MIN_SHEET = 64;

  static PackResult pack(List<SpriteSize> sizes) {
    return pack(sizes, new PackOptions(4096, 4096, false));
  }

  // MaxRects best-short-side-fit packing over a growing power-of-two sheet.
  static PackResult pack(List<SpriteSize> sizes, PackOptions opts) {
    if (sizes.isEmpty()) {
      throw new PackError("empty", "Nothing to pack — add at least one sprite.");
    }
    for (SpriteSize s : sizes) {
      if (s.w() <= 0 || s.h() <= 0) {
        throw new PackError("invalid", "Sprite \"" + s.id() + "\" needs positive pixel dimensions.");
      }
      for (SpriteSize seen : sizes) {
        if (seen == s) break;
        if (seen.id().equals(s.id())) {
          throw new PackError("invalid", "Duplicate sprite id \"" + s.id() + "\".");
        }
      }
    }

    // Biggest sprites first (max side, then area, then id). Ids are unique
    // (validated above), so the key is a total order and sort stability
    // cannot change the result.
    List<SpriteSize> order = new ArrayList<>(sizes);
    order.sort(
        Comparator.comparingInt((SpriteSize s) -> -Math.max(s.w(), s.h()))
            .thenComparingInt(s -> -s.w() * s.h())
            .thenComparing(s -> s.id()));

    int sheetW = pow2floor(Math.min(MIN_SHEET, opts.maxWidth()));
    int sheetH = pow2floor(Math.min(MIN_SHEET, opts.maxHeight()));
    for (;;) {
      Object attempt = tryPack(order, sheetW, sheetH, opts.allowRotate());
      if (attempt instanceof List) {
        @SuppressWarnings("unchecked")
        List<PackedRect> placed = (List<PackedRect>) attempt;
        return finish(sizes, placed);
      }

      String failed = (String) attempt;
      int nextW = sheetW <= sheetH ? sheetW * 2 : sheetW;
      int nextH = sheetW <= sheetH ? sheetH : sheetH * 2;
      if (nextW > opts.maxWidth() || nextH > opts.maxHeight()) {
        throw new PackError(
            "overflow",
            "\""
                + failed
                + "\" does not fit within "
                + opts.maxWidth()
                + "×"
                + opts.maxHeight()
                + " — split the batch or raise the cap.");
      }
      sheetW = nextW;
      sheetH = nextH;
    }
  }

  // One MaxRects pass over a fixed candidate sheet: all rects, or the first
  // id that failed (a String).
  private static Object tryPack(List<SpriteSize> order, int W, int H, boolean allowRotate) {
    List<FreeRect> free = new ArrayList<>();
    free.add(new FreeRect(0, 0, W, H));
    List<PackedRect> placed = new ArrayList<>(order.size());
    for (SpriteSize s : order) {
      int[] best = bestFit(free, s, allowRotate);
      if (best == null) return s.id();
      FreeRect f = new FreeRect(best[0], best[1], best[2], best[3]);
      placed.add(new PackedRect(s.id(), f.x(), f.y(), best[4], best[5], best[6] == 1));
      free = splitFree(free, placed.get(placed.size() - 1));
    }
    return placed;
  }

  // Best short side fit, ties broken by the long side, then by first-seen
  // free rect. Returns {fx, fy, fw, fh, w, h, rotated} or null.
  private static int[] bestFit(List<FreeRect> free, SpriteSize s, boolean allowRotate) {
    int[] best = null;
    int bestShort = 0, bestLong = 0;
    int[][] cands = {{s.w(), s.h(), 0}};
    if (allowRotate && s.w() != s.h()) {
      cands = new int[][] {{s.w(), s.h(), 0}, {s.h(), s.w(), 1}};
    }
    for (FreeRect f : free) {
      for (int[] c : cands) {
        if (c[0] > f.w() || c[1] > f.h()) continue;
        int leftoverW = f.w() - c[0];
        int leftoverH = f.h() - c[1];
        int shortSide = Math.min(leftoverW, leftoverH);
        int longSide = Math.max(leftoverW, leftoverH);
        if (best == null || shortSide < bestShort || (shortSide == bestShort && longSide < bestLong)) {
          best = new int[] {f.x(), f.y(), f.w(), f.h(), c[0], c[1], c[2]};
          bestShort = shortSide;
          bestLong = longSide;
        }
      }
    }
    return best;
  }

  // MaxRects split: carve the placed rect out of every free rect it touches,
  // then prune contained ones (the j<i clause keeps exactly one of an
  // identical pair).
  private static List<FreeRect> splitFree(List<FreeRect> free, PackedRect p) {
    List<FreeRect> next = new ArrayList<>();
    for (FreeRect f : free) {
      boolean intersects =
          p.x() < f.x() + f.w() && p.x() + p.w() > f.x()
              && p.y() < f.y() + f.h() && p.y() + p.h() > f.y();
      if (!intersects) {
        next.add(f);
        continue;
      }
      if (p.x() > f.x()) next.add(new FreeRect(f.x(), f.y(), p.x() - f.x(), f.h()));
      if (p.x() + p.w() < f.x() + f.w())
        next.add(new FreeRect(p.x() + p.w(), f.y(), f.x() + f.w() - (p.x() + p.w()), f.h()));
      if (p.y() > f.y()) next.add(new FreeRect(f.x(), f.y(), f.w(), p.y() - f.y()));
      if (p.y() + p.h() < f.y() + f.h())
        next.add(new FreeRect(f.x(), p.y() + p.h(), f.w(), f.y() + f.h() - (p.y() + p.h())));
    }
    List<FreeRect> kept = new ArrayList<>(next.size());
    for (int i = 0; i < next.size(); i++) {
      boolean keep = true;
      for (int j = 0; j < next.size(); j++) {
        if (j != i && contains(next.get(j), next.get(i))
            && !(contains(next.get(i), next.get(j)) && j > i)) {
          keep = false;
          break;
        }
      }
      if (keep) kept.add(next.get(i));
    }
    return kept;
  }

  private static boolean contains(FreeRect outer, FreeRect inner) {
    return outer.x() <= inner.x() && outer.y() <= inner.y()
        && outer.x() + outer.w() >= inner.x() + inner.w()
        && outer.y() + outer.h() >= inner.y() + inner.h();
  }

  // Reorder to input order and round the bounding box up to power-of-two
  // sheet dims.
  private static PackResult finish(List<SpriteSize> sizes, List<PackedRect> placed) {
    int bw = 1, bh = 1;
    for (PackedRect p : placed) {
      bw = Math.max(bw, p.x() + p.w());
      bh = Math.max(bh, p.y() + p.h());
    }
    List<PackedRect> rects = new ArrayList<>(sizes.size());
    for (SpriteSize s : sizes) {
      for (PackedRect p : placed) {
        if (p.id().equals(s.id())) {
          rects.add(p);
          break;
        }
      }
    }
    return new PackResult(pow2ceil(bw), pow2ceil(bh), rects);
  }

  private static int pow2ceil(int n) {
    int p = 1;
    while (p < n) p *= 2;
    return p;
  }

  private static int pow2floor(int n) {
    int p = 1;
    while (p * 2 <= n) p *= 2;
    return p;
  }

  // Generic JSON atlas: one frame entry per sprite (assembled manually so
  // the entries stay in pack-input order), sheet metadata for engines.
  static String atlasJson(String name, PackResult r) {
    StringBuilder out = new StringBuilder("{\n  \"frames\": {");
    for (int i = 0; i < r.rects().size(); i++) {
      PackedRect rect = r.rects().get(i);
      if (i > 0) out.append(',');
      out.append("\n    ")
          .append(jsonStr(rect.id()))
          .append(": {\n      \"frame\": {\n")
          .append("        \"x\": ").append(rect.x()).append(",\n")
          .append("        \"y\": ").append(rect.y()).append(",\n")
          .append("        \"w\": ").append(rect.w()).append(",\n")
          .append("        \"h\": ").append(rect.h()).append("\n")
          .append("      },\n")
          .append("      \"rotated\": ").append(rect.rotated()).append("\n")
          .append("    }");
    }
    out.append("\n  },\n  \"meta\": {\n")
        .append("    \"size\": {\n")
        .append("      \"w\": ").append(r.sheetW()).append(",\n")
        .append("      \"h\": ").append(r.sheetH()).append("\n")
        .append("    },\n")
        .append("    \"name\": ").append(jsonStr(name)).append("\n")
        .append("  }\n}");
    return out.toString();
  }

  // Minimal JSON string escaping (the atlas ids are plain slugs).
  private static String jsonStr(String s) {
    StringBuilder out = new StringBuilder(s.length() + 2).append('"');
    for (int i = 0; i < s.length(); i++) {
      char c = s.charAt(i);
      if (c == '"' || c == '\\') {
        out.append('\\').append(c);
      } else if (c < 0x20) {
        out.append(String.format("\\u%04x", (int) c));
      } else {
        out.append(c);
      }
    }
    return out.append('"').toString();
  }

  // One .sprite-<id> class per rect, positioned against the shared sheet
  // image.
  static String spriteCss(PackResult r, String sheetName) {
    StringBuilder out = new StringBuilder();
    for (int i = 0; i < r.rects().size(); i++) {
      PackedRect rect = r.rects().get(i);
      if (i > 0) out.append('\n');
      out.append(".sprite-").append(rect.id()).append(" {\n")
          .append("  width: ").append(rect.w()).append("px;\n")
          .append("  height: ").append(rect.h()).append("px;\n")
          .append("  background-image: url('").append(sheetName).append("');\n")
          .append("  background-position: -").append(rect.x()).append("px -")
          .append(rect.y()).append("px;\n")
          .append("}");
    }
    return out.toString();
  }
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →