addTextWatermarkUint8List method

  1. @override
Future<Uint8List?> addTextWatermarkUint8List(
  1. String filePath,
  2. Uint8List? bytes,
  3. String text,
  4. int x,
  5. int y,
  6. int textSize,
  7. Color color,
  8. Color? backgroundTextColor,
  9. int? backgroundTextPaddingTop,
  10. int? backgroundTextPaddingBottom,
  11. int? backgroundTextPaddingLeft,
  12. int? backgroundTextPaddingRight,
)
override

Adds a text watermark to the image at the specified location with the given parameters.

Returns a Uint8List representing the watermarked image.

Implementation

@override
Future<Uint8List?> addTextWatermarkUint8List(
  String filePath,
  Uint8List? bytes,
  String text,
  int x,
  int y,
  int textSize,
  Color color,
  Color? backgroundTextColor,
  int? backgroundTextPaddingTop,
  int? backgroundTextPaddingBottom,
  int? backgroundTextPaddingLeft,
  int? backgroundTextPaddingRight,
) async {
  final ui.Image image = await decodeImageFromList(bytes!);

  final recorder = ui.PictureRecorder();
  final canvas = Canvas(recorder);

  // Create a transparent background
  final bgPaint = Paint()..color = Colors.transparent;
  canvas.drawRect(
    Rect.fromLTWH(0, 0, image.width.toDouble(), image.height.toDouble()),
    bgPaint,
  );

  canvas.drawImage(image, Offset.zero, Paint());

  final textStyle = ui.TextStyle(
    color: color,
    fontSize: textSize.toDouble(),
  );

  final paragraphBuilder = ui.ParagraphBuilder(ui.ParagraphStyle(
    textAlign: TextAlign.start,
    fontSize: textSize.toDouble(),
  ))
    ..pushStyle(textStyle)
    ..addText(
      text,
    );

  final paragraph = paragraphBuilder.build()
    ..layout(ui.ParagraphConstraints(width: image.width.toDouble()));

  if (backgroundTextColor != null) {
    final bgPaintText = Paint()..color = backgroundTextColor;
    final backgroundRect = Rect.fromLTRB(
      x.toDouble() - (backgroundTextPaddingLeft ?? 0),
      y.toDouble() - (backgroundTextPaddingTop ?? 0),
      x + paragraph.width + (backgroundTextPaddingRight ?? 0),
      y + paragraph.height + (backgroundTextPaddingBottom ?? 0),
    );
    canvas.drawRect(backgroundRect, bgPaintText);
  }

  canvas.drawParagraph(
    paragraph,
    Offset(x.toDouble(), y.toDouble()),
  );

  final picture = recorder.endRecording();
  final img = await picture.toImage(image.width, image.height);
  final byteData = await img.toByteData(format: ui.ImageByteFormat.png);

  return byteData!.buffer.asUint8List();
}