addTextWatermarkToBytes static method

Future<Uint8List> addTextWatermarkToBytes(
  1. Uint8List bytes,
  2. String text, {
  3. Color color = Colors.white,
  4. double fontSize = 18,
  5. Offset offset = const Offset(10, 10),
})

给图片字节数据添加文字水印

Implementation

static Future<Uint8List> addTextWatermarkToBytes(Uint8List bytes, String text,
    {Color color = Colors.white,
    double fontSize = 18,
    Offset offset = const Offset(10, 10)}) async {
  // 解码图片数据
  final ui.Codec codec = await ui.instantiateImageCodec(bytes);
  final ui.FrameInfo frame = await codec.getNextFrame();

  // 创建 Canvas 并绘制水印
  final pictureRecorder = ui.PictureRecorder();
  final canvas = Canvas(pictureRecorder);
  canvas.drawImage(frame.image, Offset.zero, Paint());

  final textPainter = TextPainter(
    text: TextSpan(
      text: text,
      style: TextStyle(
        color: color,
        fontSize: fontSize,
      ),
    ),
    textDirection: TextDirection.ltr,
  );
  textPainter.layout();
  textPainter.paint(canvas, offset);

  // 将 Canvas 转换为图片数据
  final picture = pictureRecorder.endRecording();
  final image = await picture.toImage(frame.image.width, frame.image.height);
  final data = await image.toByteData(format: ui.ImageByteFormat.png);
  return data?.buffer.asUint8List() ?? Uint8List(0);
}