flutter怎么给图片加水印
时间: 2024-02-01 16:03:43 浏览: 111
给图片加水印 一段代码就可以实现
Flutter中给图片加水印的步骤如下:
1. 将图片加载到内存中,可以使用`ImageProvider`或`File`类来加载。
2. 创建一个新的画布,并将原始图片绘制到画布上。
3. 在画布上绘制水印,可以使用`TextPainter`类来绘制文字水印,或使用`ImageProvider`类来加载图片水印。
4. 将绘制完水印的画布保存为新的图片文件。
下面是一个简单的示例代码:
```dart
import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'package:image/image.dart' as img;
class WatermarkImage extends StatefulWidget {
final String imagePath;
final String watermarkText;
WatermarkImage({required this.imagePath, required this.watermarkText});
@override
_WatermarkImageState createState() => _WatermarkImageState();
}
class _WatermarkImageState extends State<WatermarkImage> {
late String _watermarkImagePath;
@override
void initState() {
super.initState();
_addWatermarkToImage();
}
Future<void> _addWatermarkToImage() async {
final directory = await getTemporaryDirectory();
final imageFile = File(widget.imagePath);
final image = img.decodeImage(imageFile.readAsBytesSync())!;
final watermark = img.Image.fromBytes(
100,
50,
img.encodePng(img.copyResize(
img.decodeImage(
(await rootBundle.load('assets/images/watermark.png')).buffer.asUint8List(),
)!,
width: 100,
height: 50,
)),
);
final textPainter = TextPainter(
text: TextSpan(
text: widget.watermarkText,
style: TextStyle(
fontSize: 20,
color: Colors.white,
),
),
textDirection: TextDirection.ltr,
)..layout();
final canvas = img.Canvas(image);
canvas.drawImage(watermark, 0, 0);
canvas.drawImage(
img.copyResize(
img.Image.fromBytes(
textPainter.width.toInt(),
textPainter.height.toInt(),
img.encodePng(
(await textPainter.toPicture().toImage(textPainter.width.toInt(), textPainter.height.toInt()))
.toByteData(format: img.PixelFormat.rgba8888)!
.buffer
.asUint8List(),
),
),
width: 100,
height: 50,
),
image.width - 100,
image.height - 50,
);
final watermarkImageFile = File('${directory.path}/watermark_${DateTime.now().millisecondsSinceEpoch}.jpg');
watermarkImageFile.writeAsBytesSync(img.encodeJpg(image));
setState(() {
_watermarkImagePath = watermarkImageFile.path;
});
}
@override
Widget build(BuildContext context) {
return _watermarkImagePath != null
? Image.file(
File(_watermarkImagePath),
fit: BoxFit.cover,
)
: Container();
}
}
```
这个示例代码将加载指定路径的图片文件,并在右下角添加一个水印图标和文字水印。最终生成的带有水印的新图片文件将保存在应用程序的临时目录中。
阅读全文