Image Info

Display image dimensions and size

  1. // ==UserScript==
  2. // @name Image Info
  3. // @namespace http://tampermonkey.net/
  4. // @version 0.5
  5. // @description Display image dimensions and size
  6. // @author Ram (https://www.soren.in)
  7. // @match *://*/*
  8. // @grant none
  9. // @license MIT
  10. // ==/UserScript==
  11.  
  12. (function() {
  13. 'use strict';
  14.  
  15. function getImageInfo(img) {
  16. let width = img.naturalWidth;
  17. let height = img.naturalHeight;
  18. let size = null;
  19.  
  20. fetch(img.src, { method: 'HEAD' })
  21. .then(response => {
  22. if (response.ok) {
  23. size = response.headers.get('content-length');
  24. if (size) {
  25. size = formatBytes(parseInt(size, 10));
  26. displayInfo(img, width, height, size);
  27. } else {
  28. displayInfo(img, width, height, "Size Unavailable");
  29. }
  30. } else {
  31. displayInfo(img, width, height, "Size Unavailable");
  32. }
  33. })
  34. .catch(error => {
  35. console.error("Error fetching image size:", error);
  36. displayInfo(img, width, height, "Size Unavailable");
  37. });
  38. }
  39.  
  40. function formatBytes(bytes, decimals = 2) {
  41. if (!+bytes) return "0 Bytes";
  42.  
  43. const k = 1024;
  44. const dm = decimals < 0 ? 0 : decimals;
  45. const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
  46. const i = Math.floor(Math.log(bytes) / Math.log(k));
  47.  
  48. return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`;
  49. }
  50.  
  51. function displayInfo(img, width, height, size) {
  52. let infoDiv = document.createElement('div');
  53. infoDiv.style.cssText = `
  54. position: absolute;
  55. background-color: rgba(0, 0, 0, 0.7);
  56. color: white;
  57. padding: 5px;
  58. font-size: 12px;
  59. z-index: 9999;
  60. pointer-events: none;
  61. white-space: nowrap;
  62. `;
  63.  
  64. infoDiv.innerHTML = `
  65. ${width} x ${height}<br>
  66. ${size}<br>
  67. `;
  68.  
  69. infoDiv.style.top = img.offsetTop + "px";
  70. infoDiv.style.left = img.offsetLeft + "px";
  71.  
  72. img.parentNode.insertBefore(infoDiv, img.nextSibling);
  73.  
  74. img.addEventListener('load', function() {
  75. infoDiv.style.top = img.offsetTop + "px";
  76. infoDiv.style.left = img.offsetLeft + "px";
  77. });
  78.  
  79. img.addEventListener('error', function() {
  80. infoDiv.remove();
  81. });
  82. }
  83.  
  84. const images = document.querySelectorAll('img');
  85. images.forEach(img => {
  86. if (img.complete) {
  87. getImageInfo(img);
  88. } else {
  89. img.addEventListener('load', () => getImageInfo(img));
  90. }
  91. });
  92.  
  93. })();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址