findTrim function
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 && getAlpha(c) != 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];
}