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}) {
  int h = src.height;
  int w = src.width;

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

  int xmin = w;
  int xmax = 0;
  int ymin;
  int ymax = 0;

  for (int y = 0; y < h; ++y) {
    bool first = true;
    for (int x = 0; x < w; ++x) {
      int c = src.getPixel(x, y);
      if ((mode == TrimMode.transparent && getAlpha(c) != 0) && (c != bg)) {
        if (xmin > x) {
          xmin = x;
        }
        if (xmax < x) {
          xmax = x;
        }
        if (ymin == null) {
          ymin = y;
        }

        ymax = y;

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

  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];
}