Is there a way to obtain the dimensions of an image link in Angular?

Looking to verify the dimensions of an image link, specifically if it is 1000px x 1000px and in jpg format.

For example:

https://www.w3schools.com/bootstrap/paris.jpg

I have this link and need to extract the width and height of the image.

Determining the jpg format should be straightforward, I can simply check the file extension. However, I'm unsure how to fetch the image size in angular.

Any suggestions or insights on how to accomplish this task? Thank you.

Answer №1

Check out the JavaScript implementation below:

function retrieveImageDimensions(imgUrl){

   let img = new Image(); 

   img.src = imgUrl;
   img.onload = function (event) {
        let loadedImage = event.currentTarget;
        let width = loadedImage.width;
        let height = loadedImage.height;
        console.log('height: '+height);
        console.log('width: '+width);
   } 
}

const imageUrl= "https://www.w3schools.com/bootstrap/paris.jpg";
retrieveImageDimensions(imageUrl);

You can also explore a working example for Angular here:

Working Demo

Answer №2

After struggling to access the image height and width outside of the callback function in previous solutions, I finally found a solution that worked for me. Here's what did the trick:

const image = new Image();
image.src = "https://yourImageSource";

Now, you can easily get the image height and width using image.naturalHeight and image.naturalWidth.

Just a heads up, this method worked perfectly in my Angular project with modern browsers.

Answer №3

Implement a custom directive and utilize it in the following manner:

import { Directive,ElementRef,Renderer} from '@angular/core';

@Directive({
  selector:"[imgSize]",
  host:{
    '(click)':"calculateSize()"
  }
})

export class ImageDimensionsDirective{ 

  constructor(private img:ElementRef){

  }
  calculateSize(){
    console.log('Height:' + this.img.nativeElement.offsetHeight);
    console.log('Width:' + this.img.nativeElement.offsetWidth);   
  }
}
<img imgSize [src]="imageUrl">

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 inform TypeScript that the process is defined rather than undefined?

When I execute the code line below: internalWhiteList = process.env.INTERNAL_IP_WHITELIST.split( ',' ) An error pops up indicating, Object is possibly undefined. The env variables are injected into process.env through the utilization of the mod ...

Why the CoreModule in Angular is a must-have for practical development

Though I have gained ample experience in developing Angular-UIs, there is one concept that continues to elude me - the true value of incorporating a CoreModule. To clarify, I understand the purpose of a SharedModule; it houses reusable components (such as ...

Avoiding the occurrence of routing errors when an error arises in Angular 2

I've observed that whenever an error occurs in my Angular 2 application, it also disrupts the routing. Is there a method to address this and avoid the issue of breaking routing? ...

Typescript: Understanding the question mark usage on arrays

In this example, I have the basic structure of my code: let myArray: (Array<any> | null); if (cnd) { myArray = []; myArray?.push(elt); // Curious about this line myArray[0].key = value; // Questioning this line } else { myArray = null; } Wh ...

I am currently working on integrating a dropdown menu into the navigation bar with the latest version of Bootstrap, 5.1.3

Having some trouble implementing a dropdown menu using Bootstrap. All the links are displaying the same result, which is not working for me. Below is the code I am using with Bootstrap 5.1.3: <div class="dropdown"> <button type=" ...

Enriching SpriteWithDynamicBody with Phaser3 and Typescript

Is there a way to create a custom class hero that extends from SpriteWithDynamicBody? I'm unable to do so because SpriteWithDynamicBody is only defined as a type, and we can't extend from a type in Typescript. I can only extend from Sprite, but ...

What steps should I take to display the outline of an Angular Material Icon in my Angular application?

Currently, I have <mat-icon>info<mat-icon> The result is the info icon with a filled color. However, my intention is to display just the outline of the icon. How can I achieve that? The specific icon I am looking for can be found at https:/ ...

Verify and retrieve information from the Dynamics CRM Web API with the help of Angular 2 (TypeScript)

How can one authenticate and query the Dynamics CRM Web API from a Single Page Application developed with Angular 2 (TypeScript)? Initial research indicates that: The Dynamics CRM (version 2016 or 365) instance needs to be registered as an application ...

Angular `CORS` Ailment

I am currently utilizing the MEAN stack (MongoDB, Express, Angular, and NodeJS). I have a basic function for fetching data from an external API as shown below: let api = 'https://thongtindoanhnghiep.co/api/city'; return this.http.get<any>(a ...

What is the best way to transfer PHP form data to an Angular2 application?

As I am still getting familiar with angular2/4, please bear with me if I overlook something obvious. I am currently working on updating a booking process using angular2/4. Initially, the booking procedure commences on a php website, and once some basic in ...

Preventing CORS issues when making HTTP requests to an Elasticsearch server using Angular hosted on Firebase

As someone who is a bit out of touch with web technologies, I'm pretty sure this question has been asked before. However, I am struggling to understand what CORS is and why it is causing my simple HTTP request to be blocked. I am currently working on ...

In a scenario where a specific element is disabled, how can I link its value to another related element?

Setting: Ionic version: 6.20.1 Angular CLI version: 10.0.8 In the process of developing a mobile expense management application, I am working on implementing a feature that calculates the recommended spending for different categories (e.g., home expense ...

Dynamic URL used in TRPC queries`

Is there a way to query a single post in TRPC and Next JS based on a dynamic url without using SSR or SSG? I have tried adding as string to router.query.id but encountered a TRPC error (only happening during the first load) because router.query.id is ini ...

Transforming every piece of TypeScript code into JavaScript on the server-side

I'm relatively new to developing Node.js applications for production. I've created an app using TypeScript for the backend of my Node.js project. Currently, in the package.json file, I have the following script section: "scripts": { ...

Performance problems with Ionic ion-slides due to excessive method calls

Encountering an issue with the ion-slides component where a method within my ion-slide is being called excessively, causing significant slowdown. Surprisingly, the method is triggered 900 times initially (despite showing only 100 slides) and each slight sw ...

Leverage a unified custom theme across both iOS and Android platforms in Ionic 3

My Ionic application displays distinct widgets for the iOS and Android platforms. What is the most effective method to maintain customized buttons, input boxes, etc., that are consistent across both platforms? How can I create a unified theme for all plat ...

How can I utilize a callback in TypeScript when working with interfaces?

Can someone guide me on how to implement an interface in typescript with callback function? interface LoginCallback{ Error: boolean, UserInfo: { Id: string, OrganizationId: string } } interface IntegrationInterface { Ini ...

Is there a method to obtain the compiled CSS for an Angular 2+ component?

Is it possible to retrieve compiled CSS (as a string) from an Angular2+ component? @Component({ selector: 'test-graph', templateUrl: './test-graph.component.html', styleUrls: ['./test-graph.component.scss'] }) export cla ...

Is it possible to customize webpack 4 modules in order to enable Jasmine to spy on their properties?

I've been facing issues trying to run my Jasmine test suite with webpack 4. Ever since I upgraded webpack, I keep getting this error message in almost every test: Error: <spyOn> : getField is not declared writable or has no setter The problem ...

Angular 2 Routing 3.0: Paying Attention to Letter Case

let routesList: Routes = [ { path: 'x', component: xComponent }, { path: 'y', component: yComponent }, { path: 'zComponent', component: zComponent } ]; When entering "x" in the URL, it navigates to the component page. Ho ...