resizePngFileToMaxSize function

Future<void> resizePngFileToMaxSize(
  1. String filePath,
  2. int maxSize
)

Resize a PNG file to fit within a maximum dimension.

If the image already fits, does nothing. Otherwise, scales it down proportionally to fit within maxSize on the longest edge.

Throws AppError if:

  • maxSize is not a positive integer
  • The file cannot be read or written
  • PNG decoding/encoding fails

Implementation

Future<void> resizePngFileToMaxSize(String filePath, int maxSize) async {
  if (maxSize < 1) {
    throw AppError(
      AppErrorCodes.invalidArgs,
      'Screenshot max size must be a positive integer',
    );
  }

  final file = File(filePath);
  final buffer = await file.readAsBytes();
  final source = decodePng(buffer, 'screenshot');

  final longestEdge = (source.width > source.height)
      ? source.width
      : source.height;

  if (longestEdge <= maxSize) {
    return;
  }

  final scale = maxSize / longestEdge;
  final newWidth = ((source.width * scale).round())
      .clamp(1, double.infinity)
      .toInt();
  final newHeight = ((source.height * scale).round())
      .clamp(1, double.infinity)
      .toInt();
  final resized = _resizePngBox(source, newWidth, newHeight);

  final encodedBytes = img.encodePng(resized);
  await file.writeAsBytes(encodedBytes);
}