Image Effects Creating Custom Image Cropping Interfaces in Android How to Create Simple Yet Effective PHP Overlay Understanding Real-Time Image Recognition How to add a shadow effect to an image with CSS How to crop an image in Flutter with Cloudinary How To Rotate an Image with Java Image Processing with Python Rotating an image with CSS Enhancing User Experience with a Responsive Image Slider Building a Python Image Recognition System Building an Interactive JavaScript Image Manipulation Tool Image Align Centering with HTML and CSS Efficient Image Cropping Techniques with Angular and Cloudinary Ultimate Guide to Photo Gallery on Android A Comprehensive Guide to Adding Text to Images on Android Mastering Background Changes in React Applications Comprehensive Guide on Changing Background on Android Devices Mastering Image Rotation in Java A Guide to Adding Text to Images with Python A Guide to Converting Images to Grayscale with Python Introduction Creating an Image Overlay with JavaScript Rotating an Image in Python Creating a Dynamic Photo Gallery with jQuery Creating An Interactive Photo Gallery Using JavaScript Mastering Overlay in Android Mastering Angular Overlay: A Comprehensive Guide Comprehensive Guide to Overlay in Flutter Mastering Overlay React for Responsive Design Solutions Create a Blurred Image with PHP: A Comprehensive Guide Guide to Using Blur Image in Flutter Mastering Blur Image in React Native Mastering Image Blurring in Python Mastering the Art of Image Blurring Mastering the Art of Image Blurring in Java The Ultimate Guide to Blurring Images on Android Understanding and Implementing Blur Image in JQuery An Extensive Walkthrough of Blurring Images with JavaScript How to Use HTML, CSS, and JavaScript to Make an Image Slider HTML Image Tag How to Crop GIFs? How to Align Images with CSS Ken Burns Effect – Complete Guide and How to Apply It Cartoonify – Complete Guide on Cartoonify Image Effect Mastering Web Aesthetics: A Comprehensive Guide to Gradient Fades Sepia Effect: The Ultimate Guide to the Sepia Photo Effect What is Vignette? Guide to Vignette Image Editing Pixelate – The Ultimate Guide to the Pixelation Effect How to Outline an Image: Enhancing Visual Appeal and Depth Make Your Photos Pop with Image Effects Upscale Image – Developers guide to AI-driven image upscaling Image Manipulation: History, Concepts and a Complete Guide A Full Guide to Object-aware Cropping Simplify Your Life with Automatic Image Tagging How To Resize Images In WordPress How To Create a Progress Bar For Asset Uploads Animated GIFs – What They Are And How To Create Them How To Automatically Improve Image Resolution AI Drop Shadow Get Image Dimensions From URLs Automatically Add Sepia Effect To Images Automatically Make an Image a Cartoon Automatically Add Blur Faces Effect To Images Automatically Add Background Removal Effect to an Image How to Resize an Image with React How to Easily Resize an Image with React Native

How to crop an image in Flutter with Cloudinary

crop image flutter

Image cropping is a common feature in many applications on the Internet today. Cropping an image involves removing or adjusting the edges to improve its composition or framing, drawing attention to an object in the image, or changing its size or aspect ratio. In Flutter applications, several tools and packages implement image cropping functionality. Some popular examples include Cloudinary, image_cropper, crop_your_image, and many others.

So, how do you crop images uploaded to Cloudinary in Flutter? Cloudinary is a cloud-based image and video API that provides several utilities for manipulating images, videos, GIFs, PDFs, and more.

In Cloudinary, the crop cropping mode extracts a region of the specified dimensions or a detected object from an original image. In others, cropping an image is just you removing unwanted parts of an image.

In this article, we’ll guide you through how you can use the Cloudinary Flutter SDK to crop images in your Flutter applications. Let’s get started!

In this article:

crop image flutter

Setting Up Our Flutter App

Before you continue, we assume you are familiar with Flutter. Also, ensure you have the following:

  • You should have the Flutter SDK installed on your machine. If not, follow the official installation guide to install it on your OS.
  • A Cloudinary account. You can sign up for free here. Copy your Cloudinary cloud name from your dashboard, as you’ll need it later.

java_rotate_image

There are a couple of ways to set up a Flutter application. However, in this guide, we’ll use VS Code to set it up. You can follow the instructions to create a Flutter app with VS Code here.

Run the following command in the project root directory to install the necessary packages for the application:

flutter pub add cloudinary_flutter cloudinary_url_gen

The cloudinary_flutter and cloudinary_url_gen packages make up the Cloudinary Flutter SDK, which provides an interface for integrating Cloudinary into Flutter applications.

Open the lib/main.dart file and replace its content with the following:

import 'package:cloudinary_url_gen/transformation/resize/resize.dart';
import 'package:cloudinary_url_gen/transformation/gravity/gravity.dart';
import 'package:cloudinary_url_gen/transformation/transformation.dart';
import 'package:cloudinary_flutter/image/cld_image.dart';
import 'package:flutter/material.dart';
import 'package:cloudinary_flutter/cloudinary_context.dart';
import 'package:cloudinary_url_gen/cloudinary.dart';

Note: To allow the dynamic creation of new derived assets, go to your Cloudinary dashboard and navigate to Settings > Security, then set the Strict transformation option to disabled.

Set up Cloudinary configuration

Next, add the following code to create a Cloudinary context with your cloud name:

void main() {
  // ignore: deprecated_member_use
  CloudinaryContext.cloudinary = Cloudinary.fromCloudName(cloudName: 'demo');
  runApp(const App());
}

Now, let’s go through some real examples to see how you can crop images with Cloudinary.

Crop an image to specified dimensions

The following example crops the image to a width of 1200 pixels and a height of 1200 pixels:

class App extends StatelessWidget {
  const App({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Image Cropper'),
        ),
        body: Center(
          child: SizedBox(
            width: 1200,
            height: 1200,
            child: CldImageWidget(
                publicId: "cld-sample", // Replace with the image public ID
                transformation: Transformation()
                  ..resize(Resize.crop()
                    ..gravity(Gravity.autoGravity())
                    ..width(1200)
                    ..height(1200)
                    )),
          ),
        ),
      ),
    );
  }
}

In the code above:

  • The CldImageWidget delivers a Cloudinary image. Within the widget, we can set different parameters of an image, including version, extension, urlSuffix, assetType, deliveryType, and we can pass a transformation to generate a variation of the original asset.
  • Next, we use the public ID of the image we want to crop to fetch it from Cloudinary. The Transformation object allows us to define various transformations to apply to the Cloudinary image.
  • The resize action group provides many options for resizing and cropping assets, including padding, scaling, fitting, adding a specific height and width, specifying gravity, and more.

Here’s the output:

crop image flutter

Cropping an Image with the Gravity Parameter

The gravity parameter is a qualifier that determines which part of an asset to focus on. The gravity value is specified using a compass direction, which can be any of the following: northEast, north, northWest, west, southWest, south, southEast, east, or center (the default value).

The compass direction represents a location in the image. For example, the code below crops the image to a position of northEast, representing the top right corner of the image.

child: SizedBox(
            width: 1200,
            height: 1200,
            child: CldImageWidget(
              publicId: "cld-sample", // Replace with the image public ID
              transformation: Transformation().resize(
                Resize.fill()
                  ..width(250)
                  ..height(250)
                  ..gravity(CompassGravity(Compass.northEast()))
              ),
            )

Note: You need to specify the new height and width to which the image should be cropped.

Below is the cropped image.

crop image flutter

Cropping an Image to Faces

To crop an image to keep only a subject’s face, you can use the FocusOn.face() method. First, you need to import the FocusOn class:

import 'package:cloudinary_url_gen/transformation/gravity/focus_on.dart';

Then modify the code to this:

child: SizedBox(
            width: 400,
            height: 400,
            child: CldImageWidget(
                publicId: "cld-sample", // Replace with the image public ID
                transformation: Transformation().resize(
                    Resize.crop().gravity(Gravity.focusOn([FocusOn.face()])))),
          )

crop image flutter

Crop an image to fixed coordinates

We can also specify a region of the original image to crop by giving the x and y coordinates together with the region’s width and height. This method is especially useful in scenarios where your users manually select the region to crop out of the original image.

Let’s take a look at this image with an original width of 1028px and height of 687px.

<https://res.cloudinary.com/demo/image/upload/cld-sample.jpg>

crop image flutter

Say we want to crop the image to the dog’s face. We can use the x and y coordinates with height and width like so:

child: CldImageWidget(
              publicId: "cld-sample", // Replace with the image public ID
              transformation: Transformation().resize(
                Resize.crop()
                  ..width(657)
                  ..height(534)
                  ..x(1029)
                  ..y(499)
              ),
            ),

crop image flutter

The above example requires you to know the exact coordinates to crop the image to. You can use a tool like the image_cropper library to achieve this.

Final Thoughts

Cropping an image is a common technique used in many applications today. In this article, we explored how to crop images in a Flutter application using Cloudinary. You can further explore other examples in the Cloudinary documentation, such as cropping images automatically using AI detection.

Transform and optimize your images and videos effortlessly with Cloudinary’s cloud-based solutions. Sign up for free today!

Last updated: Jun 18, 2024