#javascript #html #jquery #reactjs
#javascript #HTML #jquery #reactjs
Вопрос:
Эй, ребята, я новичок в javascript и react, я хочу получить ширину и высоту изображения при его загрузке с URL-адреса изображения. Как это сделать? Помощь была бы очень признательна.
Я знаю, что это начинается с этого, но на самом деле не понимает, как продолжить..
const imageDimension = (img) => {
let reader = new FileReader();
}
Спасибо
Ответ №1:
Вы можете использовать событие загрузки:
const image = new Image();
image.addEventListener('load', () => {
console.log('image height', image.height);
console.log('image width', image.width);
})
image.src = 'http://localhost/image.png'
Ответ №2:
Прослушиватель событий «load» работает, если изображение будет загружено в браузер.
Однако, если это не так, и вы действительно не хотите, чтобы изображение было видимым, вы могли бы сделать это.
const getImageDimension = (imgUrl) => {
const img = new Image();
// set some styles to hide the img
img.src = imgUrl;
img.style.left = -9999;
img.style.position = 'absolute';
img.style.visibility = 'hidden';
// inject it into the page
document.body.appendChild(img);
// resolve when image has been injected and
// img.height and width is available
return new Promise((resolve) => {
const interval = setInterval(() => {
const height = img.naturalHeight;
const width = img.naturalWidth;
if (height amp;amp; width) {
clearInterval(interval);
document.body.removeChild(img);
resolve({
height,
width,
})
}
})
})
}
const SAMPLE_IMAGE = "https://asia.olympus-imaging.com/content/000107507.jpg";
getImageDimension(SAMPLE_IMAGE)
.then((dimension) => console.log(dimension))