compressByChunks static method

Uint8List? compressByChunks(
  1. Uint8List imageBytes,
  2. int targetSizeInBytes
)

Implementation

static Uint8List? compressByChunks(Uint8List imageBytes, int targetSizeInBytes) {
  if (imageBytes.lengthInBytes <= targetSizeInBytes) {
    return imageBytes;
  }

  int originalLength = imageBytes.lengthInBytes;
  int removeCount = originalLength - targetSizeInBytes;

  if (removeCount >= originalLength) {
    return null;
  }
  int interval = originalLength ~/ removeCount;
  List<int> result = [];

  for (int i = 0; i < originalLength; i++) {
    if (i % interval != 0 || removeCount <= 0) {
      result.add(imageBytes[i]);
    } else {
      removeCount--;
    }
  }

  return Uint8List.fromList(result);
}