compressResizeImage static method

Future<File> compressResizeImage(
  1. String path, {
  2. int quality = 90,
  3. int maxWidth = 1080,
  4. int maxHeight = 1920,
})

Compare & resize image file in path. Pass quality, maxWidth, maxHeight for output image file.

Implementation

static Future<File> compressResizeImage(String path,
    {int quality = 90, int maxWidth = 1080, int maxHeight = 1920}) async {
  // Get image properties
  final ImageProperties properties =
      await FlutterNativeImage.getImageProperties(path);

  // Create output width & height.
  int outputWidth = properties.width!;
  int outputHeight = properties.height!;

  // Re-calculate max width, max height with orientation info.
  int mWidth = maxWidth;
  int mHeight = maxHeight;
  if (properties.orientation == ImageOrientation.rotate90 ||
      properties.orientation == ImageOrientation.rotate270) {
    mWidth = maxHeight;
    mHeight = maxWidth;
  }

  // Re-calculate output width & height by comparing with original size.
  if (outputWidth > mWidth || outputHeight > mHeight) {
    final ratio = outputWidth / outputHeight;
    outputWidth = min(outputWidth, mWidth);
    outputHeight = outputWidth ~/ ratio;
    if (outputHeight > mHeight) {
      outputHeight = min(outputHeight, mHeight);
      outputWidth = (outputHeight * ratio).toInt();
    }

    // Compress output file.
    final File compressedFile = await FlutterNativeImage.compressImage(path,
        quality: quality,
        targetWidth: outputWidth,
        targetHeight: outputHeight);
    return compressedFile;
  }

  return File(path);
}