Tips for retrieving a cropped image with Croppr.js

Currently, I am developing a mobile application using Ionic 3. Within the application, I have integrated the Croppr.js library to enable image cropping before uploading it to the server. However, I am facing an issue where I am unable to retrieve the cropped image after using the library. Here is the code snippet that I have experimented with:

index.html

<link href="assets/css/croppr.min.css" rel="stylesheet" />
<script src="assets/js/croppr.min.js"></script>

profile.component.ts

ionViewDidLoad() {
    this._croppr = new Croppr('#croppr', {
      maxSize: [512, 512, 'px'],
      minSize: [128, 128, 'px'],
      onCropStart: this.onCropStart,
      onUpdate: this.onCropUpdate,
      onCropEnd: this.onCropEnd
    })
  }

  onCropEnd(data): void {
    console.log("On Crop End: ", data);
  }

  onCropUpdate(data) {
    console.log("On Crop Update: ", data);
  }

  onCropStart(data) {
    console.log("crop start: ", data)
  }

home.component.html

<img src="path/to/image.jpg" id="croppr"/>

The problem lies in the fact that the onCropEnd method only provides me with the dimensions of the cropped image and not the actual cropped image itself. Does anyone have any insights on how I can extract the cropped image as either a File or a base64 string?

Answer №1

In case you are utilizing ionic 3, the "@ionic-native/crop": "^4.7.0" plugin is available for image cropping. I have personally employed this plugin for image cropping in my ionic 3 projects.

Furthermore, I have experience with implementing image cropping features in angular using the "ng2-img-cropper" plugin. Feel free to refer to the sample code snippet below which demonstrates how this can be done in an angular project.
demo.ts :
import {ImageCropperComponent, CropperSettings, Bounds} from 'ng2-img-cropper';

 @ViewChild('cropper', undefined)
    cropper:ImageCropperComponent;  

constructor( private cropperSettings: CropperSettings ) {
        this.cropperSettings = new CropperSettings();
        this.cropperSettings.noFileInput = true;
    }

  // For selecting an image 
   fileChangeListener($event) {
        var image:any = new Image();
        var file:File = $event.target.files[0];
        var myReader:FileReader = new FileReader();
        var that = this;
        this.isfileOpen = true;
        myReader.onloadend = function (loadEvent:any) {
            image.src = loadEvent.target.result;
            that.cropper.setImage(image);
        };
        myReader.readAsDataURL(file);
    }

  // Convert cropped base64 image to actual image
     var base64Blob = this.dataURItoBlob( file );

   /**
     * Utility function to convert base64 image 
    **/
    dataURItoBlob = ( dataURI ) => {
        var binary = atob( dataURI.split( ',' )[1] );
        var array = [];
        for ( var i = 0; i < binary.length; i++ ) {
            array.push( binary.charCodeAt( i ) );
        }
        return new Blob( [new Uint8Array( array )], { type: 'image/jpeg' } );
    }

demo.html :
<img-cropper #cropper [hidden]="!isfileOpen" [image]="data" [settings]="cropperSettings"></img-cropper> 
       <br>
       <div class="file-upload"  *ngIf="!isfileOpen">
         <input id="custom-input" accept="image/*" class="textCenter" type="file" (change)="fileChangeListener($event)">
       </div>

Answer №2

Resolved the issue.

onCropFinish(coordinates: { x: number, y: number, width: number, height: number }): void {
    console.log("Cropping finished with coordinates: ", coordinates);

    const canvas = <HTMLCanvasElement>document.getElementById('myCanvas'),
      context = canvas.getContext('2d');
    const img = new Image()

    canvas.width = coordinates.width;
    canvas.height = coordinates.height;
    const loadedImage = <HTMLImageElement>document.getElementsByTagName('img')[0]
    img.src = loadedImage.src;

    context.drawImage(img, coordinates.x, coordinates.y, coordinates.width, coordinates.height, 0, 0, canvas.width, canvas.height);
    const imageDataUrl = canvas.toDataURL('image/jpeg');

    console.log("data url of cropped image", imageDataUrl)
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble changing file names in a Next.js 13 project

I've been facing an issue ever since Next.Js 13 updated the `pages` folder to a new `app` folder. Whenever I try to rename the default "Pages.tsx" file to something like "Home.tsx" or "Information.tsx", it breaks and shows a 404 Page error. The first ...

The value 'true' was returned for an attribute 'exact' that is not of boolean type

How can I resolve this warning? Sample Code const Main = (header, navigation) => { return ( <> <div> {navigation !== false && <Navigation />} </div> </> ) } I attempted this soluti ...

Instructions for adding a select dropdown feature in Angular 6 that includes a search filter. Additionally, tips on how to filter objects by their name property

I need to add an auto-complete feature in my Angular 6 app where the data is displayed as objects in a dropdown and filtered as we type. **template.html** <mat-form-field > <input matInput [matAutocomplete]="auto" [formControl]="customerFi ...

What could be the issue with this particular Ajax script?

I am facing an issue with this JavaScript code - it runs smoothly in Chrome and IE, but encounters a problem in Firefox. I need assistance in identifying the issue. Can anyone help? <script> function checkGurantee() { var gurantee = document.get ...

How can we eliminate duplicate objects in a JavaScript array by comparing their object keys?

I am trying to remove duplicate objects from an Array. For example, the object 'bison' appears twice. var beasts = [ {'ant':false}, {'bison':true}, {'camel':true}, {'duck':false}, {'bison':false} ...

How can progress bars be animated using CSS or JavaScript?

I am currently working on creating a progress bar animation, but I'm unsure whether to use CSS or JS. Can anyone provide insight on how this effect was achieved here? I am hoping to replicate it. Does anyone know if this is the code they used? I&apos ...

Methods used on a server and methods used on a client-side application

In my ASP.NET application using C# 2.0, I have created objects for a database with properties that can be called natively or through a RESTful JSON API. These objects are used to convert data into HTML for display on the website. On the site, there are se ...

how to choose the :after pseudo-element with jQuery

Below are the codes I have tried. When this popup appears, I want to be able to close the entire popbox using the close button. CSS code .bigdiv{ display:none; background-color:#efefef; box-shadow: 10px 10px 10px 100000px rgba(0, 0, 0, 0.4); ...

Vue and Summernote issue: Model content doesn't display in form when loaded from database

I am having an issue with my form that uses the Summernote wysiwyg editor multiple times. When I fill out the form, everything works correctly - the model is updated, content is displayed, and the data is saved to the database. However, when I try to edit ...

Ways to elegantly replace an object with thorough validation of its embedded properties

Consider the following code snippet: interface Human{ name:string age:number dimensions : { height:number width:number } } const base : Human ={ name:"Base", age:12, dimensions : { height:190, width:99 } }; const child ...

Utilizing Angular with the development environment of Visual Studio 2015

Having trouble setting up my angular 2 application in visual studio 2015 (with update 1). The typescript compile is throwing an error - it says 'Cannot find module '@angular/core' at import { NgModule } from '@angular/core';. I eve ...

Ways to develop a dynamic HTML TransferBox featuring a custom attribute

I am in need of developing a customized transferbox using HTML, JavaScript, and JQuery. The user should be able to select from a list of options and associate them with attributes. This selection process should involve transferring the selected options be ...

Leverage the power of an Angular component for repeated

Attempting to recycle an Angular component within the given tree structure. https://i.sstatic.net/LVvwO.png The desired component, existing-savings, is located in transfer-guide. Trying to utilize this component in retirement-contributions-information. ...

Steps for deactivating a textbox upon checkbox activation

When I try to implement the instructions from the textbook, I'm encountering an issue where clicking on the checkbox doesn't disable the textbox on my website. <form action="#"> Billing Address same as Shipping Address: <input ...

Incorporating a complex React (Typescript) component into an HTML page: A Step-by

I used to have an old website that was originally built with Vanilia Javascript. Now, I am in the process of converting it to React and encountering some issues. I am trying to render a compound React(Typescript) component on an HTML page, but unfortunatel ...

What is the best way to disconnect an ngFor loop from its original context and reconnect it to a wrapping component's context when utilized as projected content?

In my project, I've developed a custom wrapping component that accepts <div *ngFor='let item of items> as part of its projected content. My goal is to replace the immediate bindings within the projected content with those defined in the wr ...

Trouble arises with Webpack during the compilation of JavaScript files

I've been tackling a project in Laravel 5.3, smoothly using webpack until I decided to configure ES6 by adding babel packages to my npm module. This caused a code breakdown, prompting me to revert back to the initial setup. However, now every time I m ...

Saving a complicated schema in Node using Mongoose fails to save or update when encountering an error

Greetings, I am facing challenges while trying to save a complex schema in MongoDB. const itemsSchema =new Schema({ cat: {type: String, required: true}, catItems: [{ items:{type: String}, isActive: {type: Boolean, default: true} }] }) ...

Separate your objects with RXJS groupBy Observable<<Object[]>

My current scenario involves having an entries$: Observable<BooksOverviewGroup[]>;: https://i.sstatic.net/2R0Ut.jpg The task at hand is to group these entries by their respective groupId. I attempted the following approach: groupBy(books => boo ...

Experience the magic of MFA Firebase combined with the seamless flow of React

I'm currently in the process of integrating Multifactor authentication with Firebase for a user enrollment, using the setup guide available at: https://cloud.google.com/identity-platform/docs/web/mfa I'm encountering difficulties in understandin ...