Ensuring Proper Image Size Validation in Angular 5

Currently, I am in the process of developing an Angular web application, and one of the functionalities involves photo uploads.

I am looking to add validation for image size to detect if the uploaded image is too small and prompt errors accordingly.

Below is a snippet of my code:

public onImageDrop(evt: any) {
  evt.stopPropagation();
  evt.preventDefault();
  this.croppieImage = null;
  this.onCropeMode = true;
  const image: HTMLImageElement = new Image();
  const file: File = evt.dataTransfer.files[0];
  const myReader: FileReader = new FileReader();

  myReader.onloadend = ((loadEvent: any) => {
    image.src = loadEvent.target.result;
    this.croppieImage = myReader.result;
  });

  myReader.readAsDataURL(file);
  **console.log(image.height);
  console.log(image.width);**
  this.photoInDragMode = false;
  this.uplodedPhotoFileName = file.name;
  this.uplodedPhotoFileMimeType = file.type;
  this.showPhotoSaveButton = true;
  this.onCropeMode = true;
}

The issue I'm encountering lies within the lines:

    console.log(image.height);
    console.log(image.width);

Both outputs always return:

> 0
> 0

If anyone can provide assistance with resolving this matter, it would be greatly appreciated.

Thank you in advance for your help.

Answer №1

Using HTML

<input type='file'
       formControlName="img_name"
       class="form-control"
       (change)="readUrl($event)">

In TypeScript

readUrl(event: any) {
    if (event.target.files && event.target.files[0]) {

  if (event.target.files[0].type === 'image/jpeg' || 
      event.target.files[0].type === 'image/png' || 
      event.target.files[0].type ==='image/jpg') {
    if (event.target.files[0].size < 200 * 200) {/* Checking height * width*/ }
      if (event.target.files[0].size < 2000000) {/* checking size here - 2MB */ }
  }
}

Answer №2

The console logs may show 0 if the image was not fully loaded at the time of logging due to the asynchronous nature of the process.

myReader.onloadend = ((loadEvent: any) => {
    image.src = loadEvent.target.result;
    this.croppieImage = myReader.result;
  });

To ensure that the image is fully loaded before accessing its properties, you can modify the code like this:

myReader.onloadend = ((loadEvent: any) => {
    image.src = loadEvent.target.result;
    this.croppieImage = myReader.result;


  });

image.onload = function(){
  // Image has been successfully loaded
console.log(image.height);
};

Answer №3

Give this a shot

 eventListener.onload = (e) => { 
        var picture = new Image;
        this.source = e.target.result;
        picture.source = e.target.result;
        console.log(picture.width);
      }

For reference:https://example.com/edit/upload-preview-sample

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

Is there a way to directly set object parameters when a web page loads using JavaScript?

Is there a way to read params values directly into NPAPi plugin? Here is the current JS and form code: <script> var control = document.getElementById('embed'); </script> <form name="formname"> <input type=button value="In ...

What is the reason behind appending a timestamp to the URL of a JavaScript resource?

$script.ready('jui',function() { $script('<?php base_path(); ?>js/partnerScripts.js?ts=1315442861','partners'); }); Can anyone explain why there is a fixed ts=timestamp at the end of the partnerScripts.js file name? I ...

React development: How to define functional components with props as an array but have them recognized as an object

While trying to render <MyComponent {...docs} />, I encountered the following error: TypeError: docs.map is not a function Here's how I am rendering <MyComponent /> from a parent component based on a class: import * as React from &apo ...

Issue with Jquery Crop: image not updating when using cropper

Here is the code I'm working with: <link rel="stylesheet" href="style.css"> <script src="/static/js/jquery/2.1.4/jquery.min.js"></script> <script src="http://fengyuanchen.github.io/cropper/js/cropper.min.js"></script> &l ...

Decoding the enigma of addEventListener in Nuxt: Unveiling the "referenceError: window is not defined" issue

I am currently working on developing a hamburger menu, but I have encountered an error. The error message states: ReferenceError: window is not defined. The issue seems to be within the created section of the code. <script> export default { ...

Encountering problems with parsing a lengthy JSON file

Can you spot the issue here? let stringinsta = JSON.parse({ "access_token":"129261**5ea59a4da481c65", "user":{ "username":"carlos_bellesso", ...

Exploring the integration of the mongodb-stitch library within an Angular 4 application

I have been experimenting with the MongoDB Stitch service in Angular, and so far I have successfully implemented the service. However, the only way I have managed to connect to the service is by adding the js library hosted on AWS directly into the html pa ...

What is the best way to transform the words in my JavaScript array into clickable links?

I am working on a search bar that autofills words and I want to turn those autofilled words into clickable links. For example, if I type "locations" in the search bar, I want it to autofill the word "locations" and turn it into a link that directs me to pa ...

"Troubleshooting: Why is the onError event not triggering

Has anyone else experienced issues with using a third-party API to fetch YouTube thumbnails with higher resolution, sometimes resulting in a code 404 error? I've been trying to replace the image source with a default YouTube thumbnail retrieved from i ...

The remove button in the cart is malfunctioning when attempting to delete a product. I have implemented ajax for this feature, but it

This button allows users to remove a product from their cart using AJAX: cart.hbs <button href="/remove-product" id="{{this.product._id}}" class="btn btn-danger" onclick="removeProduct ,('{{this.product._ ...

Getting the number of ticks from an rxjs Observable is a simple process that involves extracting

Is there a way to track how many times this observable has run? this.clock = Observable.interval(1000).map(function(value){ if(value == 0){ return value * 100 / 60; } return value * 100 / 60; }).take(61); I would like to kno ...

Is there a way to adjust the text to match the layout in this image?

I've been working on aligning text using bootstrap, but I'm encountering some challenges What I aim to achieve: https://i.sstatic.net/F25pw.png What I have accomplished so far: https://i.sstatic.net/Uoj3Q.png This is my code snippet: &l ...

The "results per page" ajax dropdown in Yii stops working after other ajax content is loaded on the page

One of the views in Yii framework is the "Patients" view, which contains several CGridViews and other elements that are loaded via ajax after the initial view has loaded. Some of these elements are nested within multiple levels of ajax-loaded divs. Within ...

Record the cumulative amount computed using an asynchronous callback

If I use code similar to the one below, I am able to obtain the total byte size value every time a file is added. How can I log out only the total files size after it has been calculated in the fs.stat callback? var fs = require('fs'); var to ...

Using Firebase with the async pipe in Angular 5

I am struggling to implement async pipe in Angular firebase and encountering an error that I cannot resolve: ERROR Error: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe' Utilizing the Firebase NoSQL database: { "bos ...

Utilizing long polling technique with jQuery/AJAX on the server end

Currently, I am facing an issue with long polling on a single page that contains multiple pages. The problem arises when a new request is made while a previous request is still processing. Even though I attempt to abort the previous request, it completes b ...

Is there a way to invoke an AngularJS function using JavaScript without specifying the ID parameter?

I am interested in invoking an AngularJS function without relying on the use of an id parameter. My current method for calling the AngularJS function is shown below: JS File: angular.element(document.getElementById('service_search')).scope().s ...

Search MongoDB using regular expressions that disregard any punctuation marks

I'm currently working on querying a MongoDB collection to find a single item based on a string property using react-router-dom's NavLink. The challenge arises when the prop via NavLink contains hyphens instead of spaces, and there are also names ...

Tips for including a hashtag in an AJAX request

When using ajax to send messages to the server in my chat application, I encountered an issue where everything after a hashtag is omitted. I attempted to address this by encoding the message, but it resulted in other complications in the PHP code. The enco ...

Angular 6 Bootstrap Fixed Positioning

Looking to implement affix or scrollspy functionality from Bootstrap 4 into Angular 6, I've been searching for existing libraries. Came across JonnyBGod's scrollspy, but it appears to be designed for Angular 5 and uses rxjs 5. Does anyone know of ...