Skip to content

Instantly share code, notes, and snippets.

@kkukshtel
Created March 31, 2025 15:08
Show Gist options
  • Save kkukshtel/916ff3213398380e15ab06c6c8b75f84 to your computer and use it in GitHub Desktop.
Save kkukshtel/916ff3213398380e15ab06c6c8b75f84 to your computer and use it in GitHub Desktop.
get media dimensions in html
async function getImageDimensions(url, extension) {
return new Promise((resolve) => {
// Normalize the extension to lowercase
const ext = extension ? extension.toLowerCase() : '';
// For images, we can use the Image object
const imageFormats = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp', 'ico', 'tiff', 'avif', 'heic', 'heif'];
if (imageFormats.includes(ext)) {
const img = new Image();
img.onload = function() {
resolve({ width: this.width, height: this.height });
};
img.onerror = function(e) {
logMessage(`Error loading image: ${e.type}`, "error");
// For some formats that might fail in the browser but have standard dimensions,
// we can use reasonable defaults
if (['avif', 'heic', 'heif'].includes(ext)) {
// These formats might not be supported in all browsers
// Try video element as fallback for these formats
tryVideoElement(url, resolve);
} else {
resolve({ width: null, height: null });
}
};
// Add a cache-busting parameter to avoid browser caching
img.src = `${url}${url.includes('?') ? '&' : '?'}t=${new Date().getTime()}`;
}
// For video formats, we can use the video element
else if (['mp4', 'webm', 'ogg', 'mov', 'avi', 'mkv', 'flv', 'wmv', 'm4v', '3gp'].includes(ext)) {
tryVideoElement(url, resolve);
}
// For unsupported formats, we can't determine dimensions
else {
// clearTimeout(timeout);
console.log(`Unsupported format: ${ext}`);
resolve({ width: null, height: null });
}
});
// Helper function to try using a video element
function tryVideoElement(url, resolve) {
const video = document.createElement('video');
video.onloadedmetadata = function() {
// clearTimeout(timeout);
resolve({ width: this.videoWidth, height: this.videoHeight });
};
video.onerror = function(e) {
// clearTimeout(timeout);
logMessage(`Error loading video: ${e.type}`, "error");
resolve({ width: null, height: null });
};
// Add a cache-busting parameter and prevent loading the full video
video.src = `${url}${url.includes('?') ? '&' : '?'}t=${new Date().getTime()}`;
video.preload = 'metadata';
// Some browsers need this to trigger the load
video.load();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment