Created
July 20, 2023 19:36
-
-
Save rtio/b906b3f2ce7ce73ac301a872c4f5ba9f to your computer and use it in GitHub Desktop.
Check whether a webp image is animated or not with javascript on the browser
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
| /** | |
| * Check if a WebP image is animated | |
| * @param {*} url | |
| * @returns boolean | |
| */ | |
| async function isWebPAnimated(url) { | |
| try { | |
| const response = await fetch(url); | |
| const buffer = await response.arrayBuffer(); | |
| const dataView = new DataView(buffer); | |
| // Verify the signature | |
| const signature = dataView.getUint32(0, false); | |
| if (signature !== 0x52494646) { | |
| return false; | |
| } | |
| // Get the file size | |
| const fileSize = dataView.getUint32(4, true); | |
| // Find the ANIM chunk | |
| let offset = 12; | |
| while (offset < fileSize) { | |
| const chunkType = dataView.getUint32(offset, false); | |
| const chunkSize = dataView.getUint32(offset + 4, true); | |
| if (chunkType === 0x414e494d) { // ANIM chunk | |
| return true; | |
| } | |
| offset += chunkSize + 8; | |
| } | |
| return false; | |
| } catch (error) { | |
| // Error handling | |
| return false; | |
| } | |
| } | |
| // Usage example | |
| const animatedImageList = [ | |
| 'https://media.giphy.com/media/tsX3YMWYzDPjAARfeg/giphy.webp', | |
| 'https://media.giphy.com/media/v1.Y2lkPTc5MGI3NjExZDNncWpjaXRkYXY5d3dpeHR6em42bXBucnNqdXh0ZmtzMGFma3NibyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/zzALYeLqMLDa6PEV2C/giphy.webp', | |
| 'https://media.giphy.com/media/1BXa2alBjrCXC/giphy.webp', | |
| ]; | |
| const staticImageList = [ | |
| 'https://www.gstatic.com/webp/gallery/2.webp', | |
| 'https://www.gstatic.com/webp/gallery/4.webp', | |
| 'https://gstatic.com/webp/gallery/5.webp', | |
| ]; | |
| const imagesList = [...animatedImageList, ...staticImageList]; | |
| // Create a container element for the matrix | |
| const matrixContainer = document.createElement('div'); | |
| matrixContainer.style.display = 'flex'; | |
| matrixContainer.style.flexWrap = 'wrap'; | |
| // Iterate over the images list | |
| imagesList.forEach(imageUrl => { | |
| isWebPAnimated(imageUrl) | |
| .then(isAnimated => { | |
| matrixContainer.innerHTML += | |
| ` | |
| <div style="display: flex; flex-direction: column; align-items: center; border: 2px dotted red; margin: 10px;"> | |
| <label for="animated" style="color: red;">${isAnimated ? 'Animated' : 'Not animated'} WebP Image</label> | |
| <img src="${imageUrl}" alt="WebP image" id="animated" height="200"/> | |
| </div> | |
| `; | |
| }).finally(() => { | |
| document.body.appendChild(matrixContainer); | |
| }); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment