Based on other posts here, I have written this to get the dimensions and size of a file
const newImg = new Image();
newImg.onload = () => {
console.log('height ' + newImg.height);
console.log('width ' + newImg.width);
const xhr = new XMLHttpRequest();
xhr.open('GET', '.png', true);
xhr.responseType = 'arraybuffer';
xhr.onreadystatechange = function() {
if (this.readyState === this.DONE) {
console.log('size ' + this.response.byteLength);
}
};
xhr.send(null);
}
newImg.src = '.png';
While it works, I was wondering if I could bine both in one, meaning doing only either the Image onLoad
or the xhr
request ?
Based on other posts here, I have written this to get the dimensions and size of a file
const newImg = new Image();
newImg.onload = () => {
console.log('height ' + newImg.height);
console.log('width ' + newImg.width);
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://www.google./myImage.png', true);
xhr.responseType = 'arraybuffer';
xhr.onreadystatechange = function() {
if (this.readyState === this.DONE) {
console.log('size ' + this.response.byteLength);
}
};
xhr.send(null);
}
newImg.src = 'https://www.google./myImage.png';
While it works, I was wondering if I could bine both in one, meaning doing only either the Image onLoad
or the xhr
request ?
- 2 Make only the XHR request, and then create an image element from the recieved data afterwards, by transforming the actual response body content into a Data URI? – C3roe Commented Apr 21, 2020 at 8:14
2 Answers
Reset to default 6You can avoid a second network roundtrip by using a Blob and a data URI:
fetch('https://cdn.glitch./2eddb7d4-12e2-45ae-8d27-738f13fb514a%2FGOPR1017_1586689900523.JPG?v=1587457335788')
.then(r => r.arrayBuffer())
.then(buffer => {
console.log('Size: ' + buffer.byteLength)
const blob = new Blob([buffer], {type: 'image/jpeg'})
const img = new Image()
img.src = URL.createObjectURL(blob)
img.onload = function() {
console.log(img.width, img.height)
}
})
Note that you still need the onload
callback as the browser takes a bit of time to parse the image, but in this case it won't cause a network roundtrip.
I can't answer your question, but I can give you another useful info:
Image is a weird animal, it behaves differently depending on the browser, the context and the pixel density. To be sure to catch the natural dimensions of your image, use:
newImg.naturalHeight;
newImg.naturalWidth;
instead of newImg.width
or newImg.clientWidth
.
More info here: https://developer.mozilla/en-US/docs/Web/API/HTMLImageElement/naturalHeight
Have fun!