Crop and Save an Image in Flutter Without Ui

I want to make an app that can crop image in a specific aspect ratio(device ratio). But, i don't want any ui to show crop options.

Ok, here is an example,

If user tap on an image from the image list in the app the selected Image automatically (background process) crop (device ratio) & saved on the device without showing any crop related ui. How can i do this! Any function in dart by whom can crop an image without showing anything.

1

2 Answers

You can use copyCrop() with image:

Image copyCrop(Image src, int x, int y, int w, int h);

import 'dart:io';
import 'package:image/image.dart';
void main(List<String> argv) {
  String path = argv[0];
  Directory dir = Directory(path);
  List files = dir.listSync();
  List<int> trimRect;
  for (var f in files) {
    if (f is! File) {
      continue;
    }
    List<int> bytes = f.readBytesSync();
    Image image = decodeImage(bytes);
    if (image == null) {
      continue;
    }
    if (trimRect == null) {
      trimRect = findTrim(image, mode: TrimMode.transparent);
    }
    Image trimmed = copyCrop(image, trimRect[0], trimRect[1], 
                             trimRect[2], trimRect[3]);
    String name = f.path.split(RegExp(r'(/|\\)')).last;
    File('$path/trimmed-$name').writeBytesSync(encodeNamedImage(image, f.path));
  }
}

I can confirm that Jim's answer is correct. Only thing I'd like to add to his answer is how to use the findTrim() method, which the docs don't explain properly. The key to use findTrim is to have an a sample image with target aspect ratio but it should also include base negative space as background. The findTrim() function basically takes information from a sample image and you can get the x,y coordinates as well as width,height if you don't want to manually calculate the x,y coordinates. The keyword here is negative space because if you just provide a target picture(say 4:3) to the findTrim() method, the function will simply crop the image from x,y coordinates which are 0,0 in this case. Having negative space that acts as place holder will make your work easier to clip the image.

For example to auto crop any 16:9 image to 4:3, have a 4:3 sample image with 16:9 negative space background. I have added the image as well which you can save to see for yourself.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest