Search code examples
imageflutterflutter-layout

How to split/divide image in parts in Flutter


How to split an image into equal-sized parts? Just taking an image from asset and splitting it into equal parts in a grid-like manner, so that each image part can be used as a separate image.

Something similar to picture here


Solution

  • You can use this package (https://pub.dev/packages/image) to crop the image from asset with the function copyCrop. Save them to List then display like your example.

    Edit:

    I think you know how to split your image and display them like your example if you know how to crop your image so I just show you how to change from image from asset to image of image package for cropping.

    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;
    }
    

    Remember to add this import 'package:image/image.dart' as imglib;