How to Pick and Crop an Image from Gallery and Display it in Flutter?

best vpn deal

This tutorial introduces you to image_picker and image_cropper packages in flutter. Image picker package is used to pick image from Gallery or Camera of the phone. Image croppper can be used to crop an image. image_cropper package uses platform channels to communicate with native libraries uCrop in Android and TOCropViewController in iOS. The package can be used for basic photo editing like crop and rotate images.

This browser does not support the video element.

Install Packages

PS : If the app shows error while running, you should update pods. For this cd to iOS directory, and run pod repo update from the terminal

Add the image_picker and image_cropper package to pubspec.yaml as shown above.

Configure

iOS

For the image_picker to work properly, you should add the following keys to your Info.plist file, located in < project root>/ios/Runner/Info.plist as shown above. Even though you are not using camera or microphone, this should be added as these features are used by the package.

Android

On Android,add android:requestLegacyExternalStorage=”true” as an attribute to the < application > tag in AndroidManifest.xml and also add UCropActivity as shown in the above AndroidManifest.xml example

Pick and Crop Image Functions

Image picker can be used to pick image from gallery as well as camera. _getFromGallery() is our function picking the image from gallery. When the function is run for the first time in iOS, a gallery access permission pops up with the NSPhotoLibraryUsageDescription, you gave on Info.plist. Once the user gives permission he will be able to access images in the gallery from the app.

_cropImage() is our function for cropping the image. Calling the function with path of the image as attribute, will lead to the image editor UI, where the user can crop the image. The croppedImage file in the above example holds our final cropped image file.

Here we are using 3 attributes:

  1. sourcePath – Location of the image file
  2. maxWidth – Resizes the image value if width of the image is larger than the value
  3. maxHeight – Resizes the image if height of the image is larger than the value

Crop with a Fixed Aspect Ratio

Here we use aspect ratio as 1.0. This locks the aspect ratio of cropper at 1.0 and the user will be only able to crop the image in square.

Full Implementation

best vpn deal
Scroll to Top