'Cropping an image in flutter

So I've been trying really hard to crop an image according to my needs in flutter.

Problem statement: I have a screen and in that screen I show a frame while the device camera is run on the background. Now, what I want is that whenever the user clicks a photo, only the area of that image inside the frame should be kept and rest should be cropped.

What I have done so far?

  • Added a package image 3.1.3
  • Wrote code to fetch x,y coordinates of my frame.
  • Using the calculated x,y coordinates and copyCrop method from the Image package to crop the clicked image.

Now the problem is that I do not know how copyCrop works and the code right now does not give me the expected results.

final GlobalKey _key = GlobalKey();
void _getOffset(GlobalKey key) {
    RenderBox? box = key.currentContext?.findRenderObject() as RenderBox?;
    Offset? position = box?.localToGlobal(Offset.zero);
    if (position != null) {
      setState(() {
        _x = position.dx;
        _y = position.dy;
      });
    }
  }

I assign this _key to my Image.file(srcToFrameImage) and the function above yields 10, 289.125

Here 10 is the offset from x and 289.125 is the offset from y. I used this tutorial for the same.

Code to crop my image using the Image package:

var bytes = await File(pictureFile!.path).readAsBytes();
img.Image src = img.decodeImage(bytes)!;
img.Image destImage = img.copyCrop(
   src, _x!.toInt(), _y!.toInt(), src.width, src.height);
var jpg = img.encodeJpg(destImage);
await File(pictureFile!.path).writeAsBytes(jpg);
bloc.addFrontImage(File(pictureFile!.path));

Now, can anyone tell me how i can do this effectively? Right now, it does crop my image but not as I want it to be. It would be really great if someone could tell me how does copyCrop work and what is the meaning of all these different parameters that we pass into it.

Any help would be appreciated.

Edit: Frame Image

Now, as you can see, i only want the image between this frame to be kept after being captured and rest to be cropped off.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source