Browse Source

[mob][photos] Prevent face cropping out of image bounds

laurenspriem 1 year ago
parent
commit
740ca907f2
1 changed files with 10 additions and 4 deletions
  1. 10 4
      mobile/lib/utils/image_ml_util.dart

+ 10 - 4
mobile/lib/utils/image_ml_util.dart

@@ -1294,13 +1294,19 @@ Future<List<Uint8List>> generateFaceThumbnailsUsingCanvas(
       final double widthAbs = faceBox.width * img.width;
       final double widthAbs = faceBox.width * img.width;
       final double heightAbs = faceBox.height * img.height;
       final double heightAbs = faceBox.height * img.height;
 
 
+      // Prevent the face from going out of image bounds
+      final int xCrop = (xMinAbs - widthAbs / 2).round().clamp(0, img.width);
+      final int yCrop = (yMinAbs - heightAbs / 2).round().clamp(0, img.height);
+      final int widthCrop = min((widthAbs * 2).round(), img.width - xCrop);
+      final int heightCrop = min((heightAbs * 2).round(), img.height - yCrop);
+
       futureFaceThumbnails.add(
       futureFaceThumbnails.add(
         cropAndEncodeCanvas(
         cropAndEncodeCanvas(
           img,
           img,
-          x: xMinAbs - widthAbs / 2,
-          y: yMinAbs - heightAbs / 2,
-          width: widthAbs * 2,
-          height: heightAbs * 2,
+          x: xCrop.toDouble(),
+          y: yCrop.toDouble(),
+          width: widthCrop.toDouble(),
+          height: heightCrop.toDouble(),
         ),
         ),
       );
       );
       i++;
       i++;