feat: support png, gif, webp (#7947)

Co-authored-by: xuanson9699 <84961581+xuanson9699@users.noreply.github.com>
This commit is contained in:
Nam Vu
2024-11-06 08:05:05 +07:00
committed by GitHub
parent fb656d480e
commit ac0fed6402
3 changed files with 93 additions and 12 deletions

View File

@@ -115,3 +115,52 @@ export default async function getCroppedImg(
}, mimeType)
})
}
export function checkIsAnimatedImage(file) {
return new Promise((resolve, reject) => {
const fileReader = new FileReader()
fileReader.onload = function (e) {
const arr = new Uint8Array(e.target.result)
// Check file extension
const fileName = file.name.toLowerCase()
if (fileName.endsWith('.gif')) {
// If file is a GIF, assume it's animated
resolve(true)
}
// Check for WebP signature (RIFF and WEBP)
else if (isWebP(arr)) {
resolve(checkWebPAnimation(arr)) // Check if it's animated
}
else {
resolve(false) // Not a GIF or WebP
}
}
fileReader.onerror = function (err) {
reject(err) // Reject the promise on error
}
// Read the file as an array buffer
fileReader.readAsArrayBuffer(file)
})
}
// Function to check for WebP signature
function isWebP(arr) {
return (
arr[0] === 0x52 && arr[1] === 0x49 && arr[2] === 0x46 && arr[3] === 0x46
&& arr[8] === 0x57 && arr[9] === 0x45 && arr[10] === 0x42 && arr[11] === 0x50
) // "WEBP"
}
// Function to check if the WebP is animated (contains ANIM chunk)
function checkWebPAnimation(arr) {
// Search for the ANIM chunk in WebP to determine if it's animated
for (let i = 12; i < arr.length - 4; i++) {
if (arr[i] === 0x41 && arr[i + 1] === 0x4E && arr[i + 2] === 0x49 && arr[i + 3] === 0x4D)
return true // Found animation
}
return false // No animation chunk found
}