findTrim function

List<int> findTrim(
  1. Image src,
  2. {TrimMode mode = TrimMode.transparent,
  3. Trim sides = Trim.all}
)

Find the crop area to be used by the trim function. Returns the coordinates as [x, y, width, height]. You could pass these coordinates to the copyCrop function to crop the image.

Implementation

List<int> findTrim(Image src,
    {TrimMode mode = TrimMode.transparent, Trim sides = Trim.all}) {
  var h = src.height;
  var w = src.width;

  final bg = (mode == TrimMode.topLeftColor)
      ? src.getPixel(0, 0)
      : (mode == TrimMode.bottomRightColor)
          ? src.getPixel(w - 1, h - 1)
          : 0;

  var xMin = w;
  var xMax = 0;
  int? yMin;
  var yMax = 0;

  for (var y = 0; y < h; ++y) {
    var first = true;
    for (var x = 0; x < w; ++x) {
      final c = src.getPixel(x, y);
      if ((mode == TrimMode.transparent && c.a != 0) ||
          (mode != TrimMode.transparent && (c != bg))) {
        if (xMin > x) {
          xMin = x;
        }
        if (xMax < x) {
          xMax = x;
        }
        yMin ??= y;

        yMax = y;

        if (first) {
          x = xMax;
          first = false;
        }
      }
    }
  }

  // A trim wasn't found
  if (yMin == null) {
    return [0, 0, w, h];
  }

  if (sides & Trim.top == false) {
    yMin = 0;
  }
  if (sides & Trim.bottom == false) {
    yMax = h - 1;
  }
  if (sides & Trim.left == false) {
    xMin = 0;
  }
  if (sides & Trim.right == false) {
    xMax = w - 1;
  }

  w = 1 + xMax - xMin; // Image width in pixels
  h = 1 + yMax - yMin; // Image height in pixels

  return [xMin, yMin, w, h];
}