DEV Community

Cover image for Crop Images Before Upload With JavaScript
Rik Schennink
Rik Schennink

Posted on • Originally published at pqina.nl

Crop Images Before Upload With JavaScript

In this 3 minute tutorial we use CropGuide, a JavaScript image cropper, to crop images before they’re uploaded to our server without making any changes to existing file upload code.

We’ll assume that a form with a file upload field has already been set up.

Our goal is to add image editing to this field without having to modify any existing code.

Why help your users Crop Images?

  • To speed up the image upload. A lower image size results in faster uploads, improved upload stability, and less disk usage;

  • To receive better user generated content. With some guidance users can crop the important parts of an image;

  • To lower image upload friction. End users aren’t designers. If an image isn’t in our desired aspect ratio or bigger than the maximum file size they won’t always know how to fix that;

When we optimise images before uploading, we not only get better images, we also get more images because there’s less users that will exit our form out of frustration.

Using CropGuide to Crop Images

In this tutorial we’ll use CropGuide as our JavaScript image cropping solution.

CropGuide helps with:

  • Enforcing a crop aspect ratio;

  • Requiring a minimum image size;

  • Automatically scale images to a maximum size;

  • Compressing images or converting image formats;

  • Fixing image orientation issues;

Installation only takes a couple minutes and requires two steps:

  1. We create a CropGuide account
  2. We add the CropGuide <script> to our webpage
  3. Done!

CropGuide now automatically intercepts each file upload and offers an image editor to the user. We can set our image requirements in the CropGuide dashboard.

Important: Images aren’t uploaded to CropGuide, image editing happens in the browser which is great for privacy and performance.

This is what our code looks like.

<!-- The existing file input somewhere in our form -->
<input type="file" />

<!-- The script tag we just added to our page -->
<script defer src="https://cdn.crop.guide/loader/l.js?c=123ABC">
</script>
Enter fullscreen mode Exit fullscreen mode

Try out the image editor here

CropGuide works with basic file input elements but works just as well with advanced JavaScript file upload libraries.

Wrapping up

We’ve added image cropping to our website by inserting a single script tag on our webpage. There was no need to edit any server logic, or adjust any JavaScript, saving us lots of time.

Our users can now more easily upload images, resulting in higher quality images and more images uploaded. We save time correcting image problems on the server and helping users prepare their images.

Top comments (0)