Untitled

mail@pastecode.io avatar
unknown
plain_text
8 months ago
1.5 kB
2
Indexable
Never
  Stream<Uint8List> _compressImages(
    List<File> files, {
    int initialQuality = 95,
    int minQuality = 50,
    int maxIterations = 10,
    int qualityDecrementStep = 5,
    double targetSizeInKB = 150,
  }) async* {
    assert(initialQuality <= 100 && initialQuality >= minQuality,
        'Initial quality must be between minQuality and 100.');
    assert(minQuality >= 0 && minQuality <= 100,
        'MinQuality must be between 0 and 100.');
    assert(maxIterations > 0, 'MaxIterations must be greater than 0.');
    assert(qualityDecrementStep > 0, 'QualityDecrementStep must be positive.');
    assert(targetSizeInKB > 0, 'TargetSizeInKB must be positive.');

    for (File file in files) {
      double originalSizeKB = file.lengthSync() / 1024;
      if (originalSizeKB <= targetSizeInKB) {
        yield await file.readAsBytes();
        continue;
      }

      int quality = initialQuality;
      int iteration = 0;
      Uint8List? result;

      while (iteration < maxIterations && quality >= minQuality) {
        result = await FlutterImageCompress.compressWithFile(
          file.absolute.path,
          minWidth: 1080,
          minHeight: 720,
          quality: quality,
        );

        if (result != null && result.length / 1024 <= targetSizeInKB) {
          break;
        }

        quality -= qualityDecrementStep;
        iteration++;
      }

      if (result != null) {
        yield result;
      }
    }
  }
Leave a Comment