Image Crop and Upload in Angular 12

Angular 12 image crop and upload with npm ngx-image-cropper example; In this tutorial, i am going to show you on how to show image preview by creating a Base64 url in angular before upload. And as well as how to crop an image in angular, how to zoom the image, and how to scale the image in Angular.

Crop image is great feature for server space optimization. Crop image will resize image as per required size while uploading on the server. Crop image will reduce image size and optimize image before uploading to the server. Crop image will upload image with our required width and height.

Angular 12 Image Upload, Preview, Crop, Zoom and Scale Tutorial

  • Step 1 – Create New Angular App
  • Step 2 – Install ngx-image-cropper and Bootstrap Library
  • Step 3 – Import Modules on App.Module.ts File
  • Step 4 – Add Code on View File
  • Step 5 – Add Code On app.Component ts File
  • Step 6 – Start the Angular App

Step 1 – Create New Angular App

First of all, open your terminal and execute the following command on it to install angular app:

ng new my-new-app

Step 2 – Install ngx-image-cropper and Bootstrap Library

Then install bootstrap library for implement image crop and upload in angular app. So, You can install the packages by executing the following commands on the terminal:

 npm install bootstrap

Include bootstrap css into angular.json file:

...
...
    "styles": [
        "src/styles.scss",
        "node_modules/bootstrap/dist/css/bootstrap.min.css"
    ],
...
...

Once you created a new angular app and entered into the project further, you have to install and add the image cropper plugin into the angular app:

npm install ngx-image-cropper

Step 3 – Import Modules on App.Module.ts File

Go to src/directory and open app.module.ts file. And then add the following lines of into app.module.ts file:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ImageCropperModule } from 'ngx-image-cropper';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ImageCropperModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Step 4 – Add Code on View File

Ceate image upload form in angular 12 app. So, go to src/ and app.component.html and update the following code into it:

<div class="container mt-5 text-center">
  <h3 class="mb-5">Angular Image Crop Example - Laratutorials.com</h3>
  <div class="col-md-12">
    <input type="file" (change)="onFileChange($event)" />
  </div>
  <div class="col-md-8">
    <image-cropper 
      [imageChangedEvent]="imgChangeEvt" 
      [maintainAspectRatio]="true" 
      [aspectRatio]="4 / 4"
      [resizeToWidth]="256" 
      format="png" 
      (imageCropped)="cropImg($event)" 
      (imageLoaded)="imgLoad()"
      (cropperReady)="initCropper()" 
      (loadImageFailed)="imgFailed()">
    </image-cropper>
  </div>
  <div class="col-md-4">
    <h6>Image Preview</h6>
    <img [src]="cropImgPreview" />
  </div>
</div>

Step 5 – Add Code On app.Component ts File

Go to src/ directory and open app.component.ts. Then add the following code into component.ts file:

import { Component } from '@angular/core';
import { ImageCroppedEvent } from 'ngx-image-cropper';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
    imgChangeEvt: any = '';
    cropImgPreview: any = '';
    onFileChange(event: any): void {
        this.imgChangeEvt = event;
    }
    cropImg(e: ImageCroppedEvent) {
        this.cropImgPreview = e.base64;
    }
    imgLoad() {
        // display cropper tool
    }
    initCropper() {
        // init cropper
    }
    
    imgFailed() {
        // error msg
    }
}

Step 6 – Start the Angular App

Execute the following command on terminal to start angular app:

ng serve

All features and methods of ngx-image-cropper

All inputs are optional. Either the imageChangedEventimageBase64 or imageFile should be set to load an image into the cropper.

Inputs

NameTypeDefaultDescription
imageChangedEventFileEventThe change event from your file input (set to null to reset the cropper)
imageFileBlob(File)The file you want to change (set to null to reset the cropper)
imageBase64stringIf you don’t want to use a file input, you can set a base64 image directly and it will be loaded into the cropper
imageURLstringIf you don’t want to use a file input or a base64 you can set an URL to get the image from. If requesting an image from a different domain make sure Cross-Origin Resource Sharing (CORS) is allowed or the image will fail to load.
formatstringpngOutput format (png, jpeg, webp, bmp, ico) (not all browsers support all types, png is always supported, others are optional)
aspectRationumber1 / 1The width / height ratio (e.g. 1 / 1 for a square, 4 / 3, 16 / 9 …)
maintainAspectRatiobooleantrueKeep width and height of cropped image equal according to the aspectRatio
containWithinAspectRatiobooleanfalseWhen set to true, padding will be added around the image to make it fit to the aspect ratio
resizeToWidthnumber0 (disabled)Cropped image will be resized to at most this width (in px)
resizeToHeightnumber0 (disabled)Cropped image will be resized to at most this height (in px)
cropperStaticWidthnumber0 (disabled)Set Cropper Width and disable resize (in px)
cropperStaticHeightnumber0 (disabled)Set Cropper Height and disable resize (in px)
cropperMinWidthnumber0 (disabled)The cropper cannot be made smaller than this number of pixels in width (relative to original image’s size) (in px)
cropperMinHeightnumber0 (disabled)The cropper cannot be made smaller than this number of pixels in height (relative to original image’s size) (in px) (will be ignored if maintainAspectRatio is set)
cropperMaxWidthnumber0 (disabled)The cropper cannot be made bigger than this number of pixels in width (in px)
cropperMaxHeightnumber0 (disabled)The cropper cannot be made bigger than this number of pixels in height (in px)
initialStepSizenumber3 (px)The initial step size in pixels when moving the cropper using the keyboard. Step size can then be changed by using the numpad when the cropper is focused
onlyScaleDownbooleanfalseWhen the resizeToWidth or resizeToHeight is set, enabling this option will make sure smaller images are not scaled up
cropperCropperPositionTo be able to overwrite the cropper coordinates, you can use this input. Create a new object of type CropperPosition and assign it to this input. Make sure to create a new object each time you wish to overwrite the cropper’s position and wait for the cropperReady event to have fired.
roundCropperbooleanfalseSet this to true for a round cropper. Resulting image will still be square, use border-radius: 100% on resulting image to show it as round.
imageQualitynumber92This only applies when using jpeg or webp as output format. Entering a number between 0 and 100 will determine the quality of the output image.
autoCropbooleantrueWhen set to true, the cropper will emit an image each time the position or size of the cropper is changed. When set to false, you can call the crop method yourself (use @ViewChild to get access to the croppers methods).
alignImage‘left’ or ‘center’‘center’Use this to align the image in the cropper either to the left or center.
backgroundColorstringUse this to set a backgroundColor, this is useful if you upload an image of a format with transparent colors and convert it to ‘jpeg’ or ‘bmp’. The transparent pixels will then become the set color or the default value. Enter any string representing a CSS color (https://developer.mozilla.org/en-US/docs/Web/CSS/color_value).
hideResizeSquaresbooleanfalseDisables the resize-squares at the border of the cropper. This is mostly useful for Touch Devices where you can change the Size of the Cropper via Pinch-To-Zoom
disabledbooleanfalseDisables the component and prevents changing the cropper position
canvasRotationnumber0Rotate the canvas (1 = 90deg, 2 = 180deg…)
transformImageTransform{}Flip, rotate and scale image

CSS Variables

NameTypeDefaultDescription
--cropper-outline-colorstringrgba(255,255,255,0.3)The background color you see around the cropper
--cropper-overlay-colorstringrgba(255,255,255)The background color you see around the image

Outputs

NameTypeDescription
imageCroppedImageCroppedEventEmits an ImageCroppedEvent each time the image is cropped
imageLoadedLoadedImageEmits the LoadedImage when it was loaded into the cropper
cropperReadyDimensionsEmits when the cropper is ready to be interacted. The Dimensions object that is returned contains the displayed image size
startCropImagevoidEmits when the component started cropping the image
loadImageFailedvoidEmits when a wrong file type was selected (only png, gif and jpg are allowed)

Methods

To gain access to the image cropper’s methods use @ViewChild(ImageCropperComponent) imageCropper: ImageCropperComponent;

NameReturnsDescription
cropImageCroppedEventCrops the source image to the current cropper position. Be sure to set autoCrop to false if you only wish to use this function directly.

Interfaces

CropperPosition

PropertyTypeDescription
x1numberX position of first coordinate (in px)
y1numberY position of first coordinate (in px)
x2numberX position of second coordinate (in px)
y2numberY position of second coordinate (in px)

ImageTransform

PropertyTypeDescription
scalenumberScale image (1=normal, 2=2x zoom…)
rotatenumberRotation in degrees
flipHbooleanFlipped horizontally
flipVbooleanFlipped vertically

ImageCroppedEvent

PropertyTypeDescription
base64stringBase64 string of the cropped image
widthnumberWidth of the cropped image
heightnumberHeight of the cropped image
cropperPositionCropperPositionPosition of the cropper when it was cropped relative to the displayed image size
imagePositionCropperPositionPosition of the cropper when it was cropped relative to the original image size
offsetImagePositionCropperPositionPosition of the cropper when it was cropped relative to the original image size without padding when containWithinAspectRatio is true

LoadedImage

PropertyTypeDescription
original.base64stringBase64 string of the original image
original.imageHTMLImageElementHTMLImageElement of the original image
original.sizeDimensionWidth and height of the original image
transformed.base64stringBase64 string of the transformed image
transformed.imageHTMLImageElementHTMLImageElement of the transformed image
transformed.sizeDimensionWidth and height of the transformed image
exifTransformExifTransformExif transformations read from original image

Recommended Angular Posts

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *