如何在Flutter中分割图像

8iwquhpp  于 6个月前  发布在  Flutter
关注(0)|答案(2)|浏览(89)

如何将图像分割成大小相等的部分?只需从资产中取出图像,然后以网格状的方式将其分割成相等的部分,以便每个图像部分都可以用作单独的图像。
类似图片

7gyucuyw

7gyucuyw1#

你可以使用这个软件包(https://pub.dev/packages/image)通过函数copyCrop从资源中裁剪图像。保存它们到列表中,然后像你的例子一样显示。
编辑:
我想你知道如何分割你的图像,并显示他们像你的例子,如果你知道如何裁剪你的图像,所以我只是告诉你如何改变从图像资产到图像包的图像裁剪。

List<Image> splitImage(List<int> input) {
  // convert image to image from image package
  imglib.Image image = imglib.decodeImage(input);

  int x = 0, y = 0;
  int width = (image.width / 3).floor();
  int height = (image.height / 3).floor();

  // split image to parts
  List<imglib.Image> parts = List<imglib.Image>();
  for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
      parts.add(imglib.copyCrop(image, x, y, width, height));
      x += width;
    }
    x = 0;
    y += height;
  }

  // convert image from image package to Image Widget to display
  List<Image> output = List<Image>();
  for (var img in parts) {
    output.add(Image.memory(imglib.encodeJpg(img)));
  }

  return output;
}

字符串
记住将这个导入'package:image/image.dart'添加为imglib;

mf98qq94

mf98qq942#

稍微修改了hoangquyy的答案,所以你可以只将资产路径传递给函数并获得一个图像列表:

import 'package:image/image.dart' as imglib;

Future<List<Image>> splitImage(String path) async {
    imglib.Image? image = await decodeAsset(path);

    List<Image> pieces = [];
    int x = 0, y = 0;
    int width = (image!.width / 3).floor();
    int height = (image.height / 3).floor();
    for (int i = 0; i < 3; i++) {
      for (int j = 0; j < 3; j++) {
        imglib.Image croppedImage = imglib.copyCrop(image, x: x, y: y, width: width, height: height);
        pieces.add(Image.memory(imglib.encodeJpg(croppedImage)));
        x += width;
      }
      x = 0;
      y += height;
    }

    return pieces;
  }

  /* From documentation: 
   * https://github.com/brendan-duncan/image/blob/main/doc/flutter.md#convert-a-flutter-asset-to-the-dart-image-library
   */
  Future<imglib.Image?> decodeAsset(String path) async {
    final data = await rootBundle.load(path);

    // Utilize flutter's built-in decoder to decode asset images as it will be
    // faster than the dart decoder.
    final buffer = await ui.ImmutableBuffer.fromUint8List(
        data.buffer.asUint8List());

    final id = await ui.ImageDescriptor.encoded(buffer);
    final codec = await id.instantiateCodec(
        targetHeight: id.height,
        targetWidth: id.width);

    final fi = await codec.getNextFrame();

    final uiImage = fi.image;
    final uiBytes = await uiImage.toByteData();

    final image = imglib.Image.fromBytes(width: id.width, height: id.height,
        bytes: uiBytes!.buffer, numChannels: 4);

    return image;
  }

字符串

相关问题