imageMergeTransform function

Stream<Map> imageMergeTransform(
  1. Stream<Map> inputStream
)

Implementation

@pragma('vm:entry-point')
Stream<Map> imageMergeTransform(
    Stream<Map> inputStream) async* {
  Image? image;
  await for (var map in inputStream) {
    final int dx = map['dx'];
    final int dy = map['dy'];
    final int? color = map['color'];
    final Color? backgroundColor;
    if (color != null) {
      final argb = (ByteData(4)..setUint32(0, color)).buffer.asUint8List();
      backgroundColor = ColorUint8.rgba(argb[1], argb[2], argb[3], argb[0]);
    } else {
      backgroundColor = null;
    }
    final png = map['png'];
    final currentImage = decodePng(png)!;
    assert(() {
      log('input: ${currentImage.width}, ${currentImage.height}');
      return true;
    }());
    if (image == null) {
      image = currentImage;
    } else {
      final right = dx + currentImage.width;
      final bottom = dy + currentImage.height;
      final oldImage = image;
      image = Image.fromResized(oldImage,
          width: math.max(right, oldImage.width),
          height: math.max(bottom, oldImage.height));
      for (var y = 0; y < image.height; y++) {
        for (var x = 0; x < image.width; x++) {
          if (y >= dy && y < bottom && x >= dx && x < right) {
            image.setPixel(
                x,
                y,
                blendColors(
                    backgroundColor, currentImage.getPixel(x - dx, y - dy)));
          } else if (y < oldImage.height && x < oldImage.width) {
            image.setPixel(
                x, y, blendColors(backgroundColor, oldImage.getPixel(x, y)));
          }
        }
      }
    }
  }
  final result = image ?? Image.empty();
  assert(() {
    log('output: ${result.width}, ${result.height}');
    return true;
  }());
  yield result.toMap();
}