Image Crop Widget

一个 Flutter 图片裁剪组件。该组件完全用 Dart 编写,依赖项最少。

该小部件会在给定的布局空间内显示图像。在图像上方绘制一个透明的矩形覆盖层,其每个角落都有句柄。覆盖层句柄可以通过触摸进行拖动,以调整裁剪区域。

image_crop_widget

通过调用小部件状态对象上的 `cropImage()` 方法,可以将由覆盖层标记的图像区域作为新的图像对象返回。

要获取小部件的状态,您可以使用 `GlobalKey` 对象。

示例

import 'dart:ui'; // This imports the 'Image' class.

final key = GlobalKey<ImageCropState>();
Image imageObject = ...

...

ImageCrop(key: key, image: imageObject) // This could be used inside a  build method.

...
await key.currentState.rotateImage(); // Rotate the image be 90° clockwise.
final cropedImage = await key.currentState.cropImage(); // This could be used inside a 'onPress' handler method.

如何创建图像对象

通常不会直接实例化 `dart:ui` 中的 `Image` 类。而是可以将图像数据转换为 `Uint8List`,然后像这样实例化图像:

Uint8List bytes = ...
final codec = await instantiateImageCodec(bytes);
final frame = await codec.getNextFrame();
final image = frame.image;

如何显示图像对象

可以使用 Flutter 的 `Image` 小部件显示 `Image` 对象。一种方法是将图像转换为 `Uint8List` 并将其传递到小部件的内存构造函数中。请注意,该小部件与图像对象本身不是同一个 `Image` 类。

final cropedImage = await key.currentState.cropImage();
final byte = await cropedImage.toByteData(format: ui.ImageByteFormat.png);
final byteList = byte.buffer.asUint8List();

Image.memory(byteList)

如何持久化图像对象

可以将 `Image` 对象持久化到文件或数据库中。为此,您可以将图像对象转换为 `Uint8List`,然后将其写入 `File` 或数据库对象。

final cropedImage = await key.currentState.cropImage();
final byte = await cropedImage.toByteData(format: ui.ImageByteFormat.png);
final byteList = byte.buffer.asUint8List();

final imageFile = File("Some path and filename"); // You can use the path_provider package to locate the right path.
final result = await imageFile.writeAsBytes(byteList);

GitHub

https://github.com/flbaue/image_crop_widget