Is there a way to load an image onto the ngx-image-cropper without triggering the imageChangedEvent event?

My latest project involved creating a custom cropper using ngx-image-cropper, which allows for cropping and rotating images. For the sprint demo, I needed the images to be displayed as soon as the application loads without having to trigger the fileChangeEvent() event in ngx-image-cropper.

The current outcome is functioning perfectly.

By clicking on one of the links (Photo - Signature - ...), the file uploader opens up allowing me to choose a photo to crop.

https://i.sstatic.net/83Rtv.png

This is what I aim to achieve:

Upon accessing the page initially, load a file directly from my disk without needing to click on any link.

https://i.sstatic.net/zEiKF.png

Note: I am working with Angular 8.

Below is the code snippet for the image cropper:


       <mat-card-content style="padding:3% 5%; text-align: center;">
          <image-cropper [ngClass]=" loaded && showCropper && !cropped ? 'showCropper' : 'hideCropper' "
            [imageChangedEvent]="imageChangedEvent"
            [maintainAspectRatio]="false"
            [containWithinAspectRatio]="containWithinAspectRatio"
            [aspectRatio]="5 / 3"
            [cropperMinWidth]="128"
            [onlyScaleDown]="true"
            [roundCropper]="false"
            [canvasRotation]="canvasRotation"
            [transform]="transform"
            [alignImage]="'center'"
            [style.display]="showCropper ? null : 'none'"
            format="png"
            (imageCropped)="imageCropped($event)"
            (imageLoaded)="imageLoaded()"
            (cropperReady)="cropperReady($event)"
            (loadImageFailed)="loadImageFailed()"
          >
          </image-cropper>
          <img
            *ngIf="loaded && !showCropper && cropped"
            class="document-photo"
            [src]="croppedImage"
          />
          <div *ngIf="!loaded" class="divNone"></div>
          <div class="icon-image">
            <mat-icon (click)="rotateLeft()">rotate_left</mat-icon>
            <mat-icon (click)="rotateRight()">rotate_right</mat-icon>
            <mat-icon (click)="activateCrop()">crop</mat-icon>
            <mat-icon (click)="clearImage()">clear</mat-icon>
            <mat-icon (click)="validate()">check</mat-icon>
            <mat-icon>note_add</mat-icon>
          </div>
        </mat-card-content>


        <mat-list-item class="item-doc text-blue-in">
              <mat-icon class="icon-info" matTooltipPosition="above" matTooltip="Info about the photo">info</mat-icon>
              <mat-icon *ngIf="!photo" class="text-grey-in">check_box_outline_blank</mat-icon>
              <mat-icon *ngIf="photo" class="text-grey-in">check_box</mat-icon>
              <input style="visibility: hidden; display: none;" #linkPhoto type="file" (change)="fileChangeEvent($event, 'photo')"/>
              <mat-label class="doc-title text-grey-in" (click)="onLoadPhoto()" >Photo</mat-label>
              <mat-icon *ngIf="photoSent" class="icon-edit" (click)="editPhoto()">edit</mat-icon                  >
        </mat-list-item>

So, my question is: How can I load an image from my disk into ngx-image-cropper without triggering the fileChangedEvent?

Answer №1

1) To choose an image differently than the usual method of selecting from the Uploader or input file window, consider loading the image from a specific directory within the project (such as assets/images) or inputting it directly as a base64 string. Add the following input:

[imageBase64] = "imageBase64String"

The value of imageBase64String should not be (../../assets/image.jpg), but rather the actual base64 value:

(date:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQA.....)

2) According to the author:

"All inputs are optional. Either the imageChangedEvent, imageBase64, or imageFile should be set to load an image into the cropper."

Additionally,

Input imageBase64 (string):

"If you don't want to use a file input, you can set a base64 image directly and it will be loaded into the cropper"

3) To prevent console errors:

"ERROR Error: Uncaught (in promise): Event: {" isTrusted ": true}"

It is recommended to use ngIf (the implementation could be like this):

<image-cropper
  *ngIf="imageBase64String"
  [imageChangedEvent]="imageChangedEvent"
  [imageBase64]="imageBase64String"
  ...
  ></image-cropper>

4) How to add base64 data?

You can create a function e.g. getBase64FromFile(img) {...}, utilize XMLHttpRequest() + FileReader() to obtain the base64 value, and then assign it to

this.imageBase64String = (base64 as any).result

when ngx-image-cropper initializes, for example.

ngAfterViewInit (): void {
  this.getBase64FromFile('../../assets/image.jpg');
}

Interesting details can be found here

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

Modules failing to load in the System JS framework

Encountering a puzzling issue with System JS while experimenting with Angular 2. Initially, everything runs smoothly, but at random times, System JS struggles to locate modules... An error message pops up: GET http://localhost:9000/angular2/platform/bro ...

AngularJS - UI Bootstrap: Easily expand or collapse all items in the Accordion widget

I have created a code to open and close all tabs of an accordion individually using separate 'open' and 'close' buttons. However, it requires me to dynamically add a key value pair (a Boolean value) to my JSON data. What is the best ap ...

The query does not produce a match when using the LIKE operator with the retrieved ajax data

My goal is to sync up profiles in my MySQL database with the names and skillsets dropped into my droppable div. At this link, you can find a snippet of code for reference. I am facing two main issues - firstly, the error message mysql_fetch_array() expects ...

What is the best way to implement autoplay sound on a JavaScript webpage?

I'm currently working on a web system aimed at monitoring values from a database, and I have the requirement to trigger a sound alert when a specific range of values is received. Despite trying various examples found online, none of them have been suc ...

The Ember.run.throttle method is not supported by the Object Function as it does not have a throttle method within the Ember.Mixin

I have a controller that has an onDragEvent function: controller = Em.Object.create( { onDragEvent: function() { console.log("Drag Event"); } }); Additionally, I have a Mixin called 'Event': Event = Ember.Mixin.create( { at ...

simultaneous window access

Currently, I am utilizing jsf 1.2 with a4j. One issue I have encountered is that whenever an AJAX request is made, GIF animated images appear on the page. <a4j:status> <f:facet name="start"> <h:graphicImage value="/images/ajaxLoading.g ...

How to avoid property sharing in Angular recursive components

I am currently working on a recursive component that generates a tree structure with collapsible functionality. However, I am facing an issue where the state variable active is being shared among child components. Is there a way to prevent this from happen ...

JQuery error: Unsupported property or method for converting to lowercase

I've been grappling with this issue for the past week. Here's the scenario: I've been tasked with transitioning a SharePoint application out of SharePoint and into its own website. With our current SharePoint version being 2007, an upgrade ...

Can you explain the distinction between using tsserver and eslint for linting code?

As I work on setting up my Neovim's Native LSP environment, a question has arisen regarding JS/TS linter. Could someone explain the distinction between tsserver and eslint as linters? I understand that tsserver is a language server offering features ...

The Redux Toolkit Slice Reducer fails to function properly when incorporating an extra Reducer that is not compatible

I am relatively new to the world of Redux and have been attempting to use RTK right from the start. It has been quite a challenging and confusing experience for me so far. Recently, I decided to include a standard Reducer instead of an extraReducer in my ...

Encountering an ng build error while attempting to include a factory in the providers array

Currently, I am working on a school project where I implemented a basic HttpFactory and included it in the provider section of app.module.ts. However, upon running ng build, I encountered the following error: ERROR in Cannot read property 'provide& ...

How to create a see-through background using three.js

I am new to working with three.js and recently came across a codepen that caught my attention. However, I am facing difficulties while trying to change the background color. After exploring various questions related to this issue, I attempted to add { alp ...

Has anyone tried integrating Reveal JS with Angular 8?

Encountering a problem with the integration of Reveal JS in an Angular component. Despite being initialized after DOM processing, it is not displaying anything. What is the appropriate time to initialize the reveal library? Is there a way to incorporate ...

Requiring addresses for Google Maps in order to display directions

To display the directions between two addresses based on the chosen transportation mode, I need to pass the addresses to the code in page 2. After the user selects two cities from a Dropdown box on page 1, they will be sent to the code to show their locati ...

When validating an array in JavaScript, it is important to note that not all elements may be displayed. Only the last variable of each element will

I am encountering an issue with validating an array of objects, specifically a table with rows where each row represents an object. The problem is that no error message appears if there is an error in the middle row of the table. However, if there's a ...

Tips on manually refreshing AngularJS view using ControllerAs syntax?

As I work on creating a user-friendly dashboard with widgets that can be sorted, docked, and floated, I encountered an issue. The controls I am using generate floating widgets as HTML at the bottom of the DOM, outside the controller scope where they were c ...

Detecting repeated keys in a query for a REST connector in loopback

Can anyone help me figure out how to duplicate parameters in a loopback REST connector query? Here's the code snippet I'm working with: details: { 'template': { 'method': 'GET', 'debug': tr ...

What happens to the parent scope in Javascript when declaring a subclass and why does it get overridden?

I have two classes in JavaScript, with one inheriting from the other. The structure is as follows: var Parent = (function(){ var self; var parent = function(){ self = this; self.type = 'Parent'; }; parent.protot ...

Utilizing MVC3 to make an Ajax call in Jquery to store data in a database

I am currently developing an MVC3 application. The script code on my view page looks like this- <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script> <script type="text/javascript"> $(function () { ...

Repairing the Performance of the 'Save' Feature

Can the 'Save' button in my code save team assignments for players selected using drag and drop? I'm considering using localStorage, but unsure about implementation. Note: To run the code properly, copy it as an HTML file on your computer. ...