Advertisement
nicolaslagios

Check image sizes in bulk, using Javascript

Aug 10th, 2023 (edited)
1,147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 1.30 KB | Source Code | 0 0
  1. //Check image sizes of current page in bulk, using Javascript in console
  2.  
  3. async function getImageContentLength(url) {
  4.     const response = await fetch(url, { method: 'HEAD' });
  5.     const contentLength = response.headers.get('Content-Length');
  6.     return parseInt(contentLength, 10);
  7. }
  8.  
  9. function formatSize(sizeInBytes) {
  10.     if (sizeInBytes < 1024) {
  11.         return sizeInBytes + ' B';
  12.     } else if (sizeInBytes < 1024 * 1024) {
  13.         return (sizeInBytes / 1024).toFixed(2) + ' KB';
  14.     } else {
  15.         return (sizeInBytes / (1024 * 1024)).toFixed(2) + ' MB';
  16.     }
  17. }
  18.  
  19. async function getImageInfo(img) {
  20.     const width = img.width;
  21.     const height = img.height;
  22.     if (width >= 100 || height >= 100) {
  23.         const src = img.src.toLowerCase();
  24.         if (
  25.             !src.startsWith('data:image/svg+xml') &&
  26.             !src.endsWith('.svg') &&
  27.             !src.includes('icon')
  28.         ) {
  29.             const size = await getImageContentLength(src);
  30.             console.log(`Image: ${src}`);
  31.             console.log(`Size: ${width}x${height}`);
  32.             console.log(`File Size: ${formatSize(size)}`);
  33.             console.log('---');
  34.         }
  35.     }
  36. }
  37.  
  38. const images = document.getElementsByTagName('img');
  39.  
  40. for (let i = 0; i < images.length; i++) {
  41.     getImageInfo(images[i]);
  42. }
  43.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement