optimizeImage method

Future<Image> optimizeImage({
  1. required Uint8List bytes,
  2. required int dotsPerLine,
})

Implementation

Future<img.Image> optimizeImage({
  required Uint8List bytes,
  required int dotsPerLine,
}) async {
  img.Image src = img.decodeJpg(bytes)!;
  src = img.grayscale(src);

  final w = src.width;
  final h = src.height;

  final res = img.Image(width: w, height: h);
  for (int y = 0; y < h; ++y) {
    for (int x = 0; x < w; ++x) {
      final pixel = src.getPixelSafe(x, y);
      final lum = img.getLuminanceRgb(pixel.r, pixel.g, pixel.b);

      img.Color c;
      final l = lum / 255;
      if (l > 0.8) {
        c = img.ColorUint8.rgb(255, 255, 255);
      } else {
        c = img.ColorUint8.rgb(0, 0, 0);
      }

      res.setPixel(x, y, c);
    }
  }

  src = res;
  src = img.copyResize(
    src,
    width: dotsPerLine,
    maintainAspect: true,
  );

  return src;
}