imageToJpeg static method

Future<Uint8List?> imageToJpeg(
  1. Image image, {
  2. int quality = 90,
  3. Color backgroundColor = Colors.white,
})

Encode a captured ui.Image to JPEG bytes.

Implementation

static Future<Uint8List?> imageToJpeg(
  ui.Image image, {
  int quality = 90,
  Color backgroundColor = Colors.white,
}) async {
  final byteData = await image.toByteData(format: ui.ImageByteFormat.rawRgba);
  if (byteData == null) return null;

  final raw = img.Image.fromBytes(
    width: image.width,
    height: image.height,
    bytes: byteData.buffer,
    bytesOffset: byteData.offsetInBytes,
    numChannels: 4,
    order: img.ChannelOrder.rgba,
  );
  final flattened = img.Image(width: raw.width, height: raw.height);
  img.fill(
    flattened,
    color: img.ColorRgb8(
      _colorChannel(backgroundColor.r),
      _colorChannel(backgroundColor.g),
      _colorChannel(backgroundColor.b),
    ),
  );
  img.compositeImage(flattened, raw);

  final normalizedQuality = quality.clamp(1, 100).toInt();
  return Uint8List.fromList(
    img.encodeJpg(flattened, quality: normalizedQuality),
  );
}