getCompressQuality static method

Future<int> getCompressQuality({
  1. required Uint8List tempImg,
  2. required int sizeLimit,
  3. required String format,
})

Implementation

static Future<int> getCompressQuality({
  required Uint8List tempImg,
  required int sizeLimit,
  required String format,
}) async {
  int quality = 50;

  int compressSize = await getCompressSize(
      uint8list: tempImg, compressSize: quality, format: format);

  if (compressSize == sizeLimit) {
    return quality;
  }

  List<int> sizeList =
      compressSize > sizeLimit ? [40, 30, 20, 10] : [90, 80, 70, 60];
  quality = sizeList.last;

  for (int i = 0; i < sizeList.length; i++) {
    compressSize = await getCompressSize(
        uint8list: tempImg, compressSize: sizeList[i], format: format);
    if (compressSize <= sizeLimit) {
      quality = sizeList[i];
      break;
    }
  }

  if (compressSize == sizeLimit) {
    return quality;
  }

  int tempvalue = quality;
  quality += 5;

  compressSize = await getCompressSize(
      uint8list: tempImg, compressSize: quality, format: format);

  if (compressSize == sizeLimit) {
    return quality;
  }

  sizeList = compressSize > sizeLimit
      ? [
          tempvalue + 4,
          tempvalue + 3,
          tempvalue + 2,
          tempvalue + 1,
        ]
      : [
          tempvalue + 9,
          tempvalue + 8,
          tempvalue + 7,
          tempvalue + 6,
        ];
  quality = sizeList.last;

  for (int i = 0; i < sizeList.length; i++) {
    compressSize = await getCompressSize(
        uint8list: tempImg, compressSize: sizeList[i], format: format);
    if (compressSize <= sizeLimit) {
      quality = sizeList[i];
      break;
    }
  }

  return quality;
}