Angular 7/8 | Image Uploader with Cropper and Preview Tutorial with Example

In this tutorial, we will implement Image selection functionality with a crop window for a user to crop any area on the browsed image and also preview the selected section of the image.

The cropper image section is converted into base64 encoded string which can be easily uploaded to the server and saved as a real image into JPG or PNG formats.

Here we will discuss the frontend part to implement Image selection and crop functionality from scratch.

Let’s get started with a new Angular 8 project.

Create an Angular Project

We will create a new Angular 8project using the NG CLI tool. Here we will use the current version on Ng CLI which is v8.3.15.

Run the following command in terminal to create a new Angular project:

Install and Configure Angular Image Cropper

After successfully creating an Angular project, next, we will install the Angular Image Cropper package which is very easy to install and use in the project. Here we will use the ngx-image-cropper package which very popular and loads of configurations which we will discuss with examples.

Installation

Run following NPM command in terminal to install Image Cropper package:

Configure App Module

To use Image Cropper anywhere in the Angular project, we will import it in our App’s main module in app.module.ts then add in the imports array as shown below:

 

Use Image Cropper

To use image cropper in a component, simply add the following three elements in the template.

Input: Input control of type file is required to select an image.

ImageCropper: The image-cropper component directive will display the selected image with a cropper area to select the portion of the actual image.

Img: The preview of the selected cropped image will be shown in the img element.

Note: We have added bootstrap.css in index.html file to beautify the layout

 

In component class, import ImageCroppedEventthen define a few variables and methods as shown below:

 

That’s it now you have a nice working Image cropper tool which will return base64 string of cropped area, which can be sent to the server to save as an image in any format.

 

 

Thanks for visiting :) Let me know if you have some suggestions or feedback for this post in the comment section. Looking for any tutorial or demo on FreakyJolly, just drop me a message here

Leave a Reply

avatar
  Subscribe  
Notify of