What is Image Cropping?
Digital images are composed of a grid of vertical and horizontal pixels—in effect, small color squares. Image cropping is a way of photo editing that involves removing a portion of an image, hence reducing the number of pixels and changing the aspect ratio. As a result, you emphasize a subject, reframe it, or direct the viewer’s attention to a certain part of the image.
You can automate image cropping with scripting languages like JavaScript.
This is part of a series of articles about Auto Image Crop.
This article:
- Crop an Image in JavaScript With HTML Canvas
- Understanding the Challenges of JavaScript Image Cropping
- Image Cropping in JavaScript Through Automation With Cloudinary
Crop an Image in JavaScript With HTML Canvas
A canvas is a white region in which you can display or draw graphical elements. A common way to crop an image in JavaScript is with the HTML5 <canvas>
element and then transform the image by calling the drawImage()
function.
Step 1: Create a Canvas in HTML
Create a <canvas>
element in your HTML document:
<canvas id="mycanvas" width="800px" height="400px"></canvas>
Next, add a script file called crop.js
through which to crop an image:
<script src="./crop.js"></script>
Step 2: Create a JavaScript File and a Crop Function
Edit the crop.js
file:
- Define a function named
cropImage()
, which you can call from within your code. - Add the
onload()
function so thatcropImage()
runs only after an image is fully loaded on the viewer’s browser.
onload()
gets the <canvas>
element from your HTML and then a 2D context object for the canvas.
const canvas = document.getElementById('mycanvas'); const context = canvas.getContext('2d');
Step 3: Load the Image
Create an image
object and load an image with the src
property from a local drive or the internet.
var image = new Image(); image.src = "https://live.staticflickr.com/47/150654741_ae02588670_b.jpg";
The image 150654741_ae02588670_b.jpg
shows a cup of coffee:
Source: Flickr
Step 4: Call the drawImage()
Function
Here’s the syntax of the drawImage()
function:
drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);
Crop operations require all nine parameters:
image, sx, sy
— The image object, the x-coordinate, and the y-coordinate from which to start cropping the image.sWidth, sHeight
— The width of the cropped version, starting fromsx
andsy
.dx, dy
— The point from which to start drawing the cropped version on the canvas.dWidth, dHeight
— The width and height of the cropped version to be displayed.
Here is how to call the drawImage()
function along with the image and context you loaded previously:
image.onload = function(){ context.drawImage(image, 100, 100, 200, 200, 50,50, 200, 200);
drawImage()
performs two steps:
- Crop a 200×200-pixel square that starts from the coordinate 100:100 pixels on the original image.
- Display the cropped version in the canvas with a top and left margin of 50 pixels.
Understanding the Challenges of JavaScript Image Cropping
Below are the issues vis-à-vis cropping images in JavaScript:
- Content-aware cropping. Most cropping operations depend on the context. For example, you don’t want to remove important parts of the image, but that’s difficult to ensure programmatically because the crop() function is not sensitive to the image content.
- Cropping and resizing. Oftentimes, you must resize and crop an image at the same time. Even though you can resize images in Python with a similar technique, combining cropping and resizing can get tricky, let alone that it’s challenging to generate the exact image you need for your design.
- Image management. A large number of crop operations might lead to multiple versions for each image, all to be stored on the server. Besides procuring extra storage space, you must also put in place a clear, consistent convention to facilitate locating the right version of the image. A much more efficient approach is to simply dynamically generate the required version of the image without saving all its versions to the file system.
To avoid those issues, leverage an advanced tool like Cloudinary, which automatically crops and transforms images.
Image Cropping in JavaScript Through Automation With Cloudinary
A cloud-based service for managing images and videos, Cloudinary offers a generous free-forever subscription plan. While on that platform, you can upload your images, apply built-in effects, filters, and modifications.
You can also resize images through automation, focusing on the most important elements with AI, or adapt them to your website design by, for example, specifying the width, height, and aspect ratio as qualifiers for the new image instances. Cloudinary then automatically performs the resizing and cropping tasks to meet the criteria. No manual efforts are required.
Take this 1,200×1,200-pixel image:
Resizing it to 200×200 pixels with crop, scale, fill, and pad results in the following images:
To automate image resizing and cropping on Cloudinary:
- Sign up for a free Cloudinary account.
- Install the JavaScript SDK.
- Set the transformation criteria for the above examples:
# Focus on the model in a portrait crop. new CloudinaryImage("docs/model.jpg").resize( fill() .width(450) .height(600) .gravity(focusOn(person())) ); # Detect the face for a thumbnail crop. new CloudinaryImage("docs/model.jpg").resize( thumbnail() .width(250) .height(250) .gravity(focusOn(face())) ); # Crop to a banner, automatically focusing on a region of interest. new CloudinaryImage("docs/model.jpg").resize( fill() .width(600) .height(150) .gravity(autoGravity()) );