Last active
October 3, 2017 05:57
-
-
Save gauravchl/6470096462a619b10392e0a7d24dd1a2 to your computer and use it in GitHub Desktop.
get image size without downloading full image,
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Currently works for jpeg only, | |
// CROS should be enable | |
// JPEG SPECS: | |
// http://vip.sugovica.hu/Sardi/kepnezo/JPEG%20File%20Layout%20and%20Format.htm | |
async function getSize(url) { | |
const response = await fetch(url); | |
const reader = response.body.getReader(); | |
const {value, done} = await reader.read(); | |
let width, height; | |
for (let i = 0; i <= value.length; i++) { | |
if (value[i] === 255 && value[i + 1] === 194) { | |
height = (value[i + 5] * 255) + value[i + 6] + 2; | |
width = (value[i + 7] * 255) + value[i + 8] + 4; | |
break; | |
} | |
} | |
reader.cancel(); | |
return {width, height} | |
} | |
getSize('https://images.unsplash.com/photo-1504964148034-86ded740d1e2?dpr=1&auto=compress,format&fit=crop&w=2850&h=&q=80&cs=tinysrgb&crop=').then(r => console.log(r)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment