Oblivion
Oblivion

Reputation: 635

How to get an img height via typescript

I'm attempting to get the height of an image after it loads. I've tried a few different ways, but offsetHeight prints 0, and the others print nothing. The elements have been loaded at the point of querying the height, as right before i query their heights, i successfully set their widths via getElementById and setAttribute calls on their id.

* {
  margin: 0;
  padding: 0;
  border: 0;
}

.gallery {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

.gallery img {
  width: 100%;
  display: block;
}

Id 6 corresponds to an image, and it does exist/has been rendered at the point of these calls in typescript.

My thinking behind bottom was that if i could get the top and bottom of the image, i could work out the height without getting it.

console.log(document.getElementById("6").offsetHeight.toString());
console.log(document.getElementById("6").offsetHeight.valueOf());
console.log(document.getElementById("6").style.height);
console.log(document.getElementById("6").style.bottom);
console.log(document.getElementById("6").style.borderBottom);

HTML

  <div id={{i}} *ngFor="let image of images; let i = index;">
    <img class="img-responsive" src={{image.src}} alt="" (click)="clicked()">
  </div>

Upvotes: 0

Views: 147

Answers (2)

Majedur
Majedur

Reputation: 3242

You can install library:

npm install image-size --save

Sample Code:

var sizeOf = require('image-size');
var dimensions = sizeOf('images/funny-cats.png');
console.log(dimensions.width, dimensions.height);

Async/Await (Typescript & ES7)

var { promisify } = require('util');
var sizeOf = promisify(require('image-size'));
try {
  const dimensions = await sizeOf('images/funny-cats.png');
  console.log(dimensions.width, dimensions.height);
} catch (err) {
  console.error(err);
}

Reference here

Hope it's help you.

Upvotes: 0

piedpiper
piedpiper

Reputation: 524

Try this -

const el: HTMLElement = document.getElementById('6');
console.log(el.offsetHeight);

Upvotes: 1

Related Questions