trim function

Image trim(
  1. Image src,
  2. {TrimMode mode = TrimMode.topLeftColor,
  3. Trim sides = Trim.all}
)

Automatically crops the image by finding the corners of the image that meet the mode criteria (not transparent or a different color).

mode can be either TrimMode.transparent, TrimMode.topLeftColor or TrimMode.bottomRightColor.

sides can be used to control which sides of the image get trimmed, and can be any combination of Trim.top, Trim.bottom, Trim.left, and Trim.right.

Implementation

Image trim(Image src,
    {TrimMode mode = TrimMode.topLeftColor, Trim sides = Trim.all}) {
  if (mode == TrimMode.transparent && src.numChannels == 3) {
    return Image.from(src);
  }

  final crop = findTrim(src, mode: mode, sides: sides);

  Image? firstFrame;
  for (var frame in src.frames) {
    final dst = firstFrame?.addFrame() ??
        Image.fromResized(frame,
            width: crop[2], height: crop[3], noAnimation: true);
    firstFrame ??= dst;

    compositeImage(dst, src,
        srcX: crop[0],
        srcY: crop[1],
        srcW: crop[2],
        srcH: crop[3],
        blend: BlendMode.direct);
  }

  return firstFrame!;
}