downsample static method
Downsamples image dimensions by the given factor (e.g. 2 = half resolution).
width and height define original image dimensions.
bytesPerPixel is typically 1 (grayscale) or 4 (RGBA).
Implementation
static Uint8List downsample(
Uint8List bytes, {
required int width,
required int height,
int factor = 2,
int bytesPerPixel = 1,
}) {
if (factor <= 1 || bytes.isEmpty) return bytes;
final clampedFactor = factor.clamp(1, 8);
final newWidth = (width / clampedFactor).ceil();
final newHeight = (height / clampedFactor).ceil();
final result = Uint8List(newWidth * newHeight * bytesPerPixel);
int outIndex = 0;
for (int y = 0; y < height && outIndex < result.length; y += clampedFactor) {
for (int x = 0; x < width && outIndex < result.length; x += clampedFactor) {
final srcIndex = (y * width + x) * bytesPerPixel;
for (int c = 0; c < bytesPerPixel && outIndex < result.length; c++) {
if (srcIndex + c < bytes.length) {
result[outIndex++] = bytes[srcIndex + c];
}
}
}
}
return Uint8List.view(result.buffer, 0, outIndex);
}