compressImage function

Future<File> compressImage(
  1. File file,
  2. int targetWidth
)

Implementation

Future<File> compressImage(File file, int targetWidth) async {
  final bytes = await file.readAsBytes();
  final image = img.decodeImage(bytes);

  if (image == null) {
    throw Exception("Invalid image file");
  }

  final imageWidth = image.width;
  final imageHeight = image.height;
  final targetHeight = (imageHeight * targetWidth / imageWidth).round();

  final resizedImage =
      img.copyResize(image, width: targetWidth, height: targetHeight);

  final compressedBytes = img.encodeJpg(resizedImage, quality: 85);
  return File(file.path)..writeAsBytesSync(compressedBytes);
}