如何从Gravatar这类无后缀图片链接中获取图片类型?
How to Get Image Type from Extension-Less URLs (Like Gravatar)
Great question! I’ve run into this exact issue with Gravatar links before—since there’s no file extension in the URL, your string-splitting tricks won’t work here. Instead, you need to check the server’s HTTP response headers when fetching the image to determine its type. Here are two reliable ways to do this in JavaScript:
1. Use the Fetch API (Modern Browsers)
This is the cleanest approach for modern environments. We use a HEAD request (instead of GET) to only fetch the response headers, which is faster since we don’t need to download the entire image file:
async function getImageFileType(url) { try { // Send a HEAD request to get just the headers const response = await fetch(url, { method: 'HEAD' }); // Extract the Content-Type header const contentType = response.headers.get('Content-Type'); // Verify it's an image and extract the type if (contentType && contentType.startsWith('image/')) { return contentType.split('/')[1]; // Returns "png", "jpeg", "webp", etc. } return null; // Not a valid image type } catch (error) { console.error('Failed to fetch image type:', error); return null; } } // Example usage with your Gravatar link getImageFileType('https://www.gravatar.com/avatar/71b0d516013802a2d67aeb7c2e77ed32?s=48&d=identicon&r=PG&f=1') .then(type => console.log('Image type:', type)); // Typically returns "png"
2. Use XMLHttpRequest (Legacy Browser Support)
If you need to support older browsers that don’t have Fetch API support, use XMLHttpRequest instead:
function getImageFileType(url, callback) { const xhr = new XMLHttpRequest(); xhr.open('HEAD', url); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status === 200) { const contentType = xhr.getResponseHeader('Content-Type'); if (contentType && contentType.startsWith('image/')) { callback(null, contentType.split('/')[1]); } else { callback('URL does not point to an image', null); } } else { callback(`Request failed with status code: ${xhr.status}`, null); } } }; xhr.send(); } // Example usage getImageFileType('https://www.gravatar.com/avatar/71b0d516013802a2d67aeb7c2e77ed32?s=48&d=identicon&r=PG&f=1', (error, type) => { if (error) { console.error(error); } else { console.log('Image type:', type); } });
Key Notes
- Why
HEADinstead ofGET? AHEADrequest only retrieves the response headers, not the entire image content. This saves bandwidth and speeds up the request. - Cross-Origin Considerations: Gravatar allows cross-origin requests, so you won’t run into CORS issues here. For other extension-less image URLs, make sure the server permits cross-origin
HEADrequests. - Cache the Result: If you need to check the same URL multiple times, cache the result to avoid redundant network requests.
内容的提问来源于stack exchange,提问作者silpa jacob
相关产品推荐
相关产品推荐

