I am working on a Flutter project that involves PNGs with arbitrarily wide transparent margins. For example, consider this cat in a box. Cat in a box
I need a way to crop off the margins without knowing where the image will be positioned. This can be done with Flutter's Image package, but I feel like there should be a more elegant solution. Here is how I am currently doing it:
int top = _findHighestPixel(decodedImage);
int bottom = _findLowestPixel(decodedImage);
int left = _findLeftmostPixel(decodedImage);
int right = _findRightmostPixel(decodedImage);
decodedImage = img.copyCrop(decodedImage, x: left, y: top, width: right - left, height: bottom - top);
Uint8List croppedByteList = img.encodePng(decodedImage);
int _findHighestPixel(img.Image decodedImage) {
for (int y = 0; y < decodedImage.height; y++) {
for (int x = 0; x < decodedImage.width; x++) {
if(decodedImage.getPixel(x, y).a != 0) {
return y;
}
}
}
return 0;
}
int _findLowestPixel(img.Image decodedImage) {
for (int y = decodedImage.height - 1; y >= 0; y--) {
for (int x = 0; x < decodedImage.width; x++) {
if(decodedImage.getPixel(x, y).a != 0) {
return y;
}
}
}
return decodedImage.height;
}
int _findLeftmostPixel(img.Image decodedImage) {
for (int x = 0; x < decodedImage.width; x++) {
for (int y = 0; y < decodedImage.height; y++) {
if(decodedImage.getPixel(x, y).a != 0) {
return x;
}
}
}
return 0;
}
int _findRightmostPixel(img.Image decodedImage) {
for (int x = decodedImage.width - 1; x >= 0; x--) {
for (int y = 0; y < decodedImage.height; y++) {
if(decodedImage.getPixel(x, y).a != 0) {
return x;
}
}
}
return decodedImage.width;
}
I would love to know if there is a simpler/faster approach than tediously iterating through all the pixels until I hit the image wall. Thanks!