Skip to content

Commit

Permalink
fix: Detect apng image type (#488)
Browse files Browse the repository at this point in the history
Co-authored-by: Shu Ding <[email protected]>
  • Loading branch information
btea and shuding authored May 24, 2023
1 parent 5db1f68 commit 7cf0b51
Showing 1 changed file with 23 additions and 1 deletion.
24 changes: 23 additions & 1 deletion src/handler/image.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

const AVIF = 'image/avif'
const WEBP = 'image/webp'
const APNG = 'image/apng'
const PNG = 'image/png'
const JPEG = 'image/jpeg'
const GIF = 'image/gif'
Expand Down Expand Up @@ -63,7 +64,7 @@ type ResolvedImageData = [string, number?, number?] | readonly []
export const cache = createLRU<ResolvedImageData>(100)
const inflightRequests = new Map<string, Promise<ResolvedImageData>>()

const ALLOWED_IMAGE_TYPES = [PNG, JPEG, GIF, SVG]
const ALLOWED_IMAGE_TYPES = [PNG, APNG, JPEG, GIF, SVG]

function arrayBufferToBase64(buffer) {
let binary = ''
Expand Down Expand Up @@ -120,6 +121,7 @@ function arrayBufferToDataUri(data: ArrayBuffer) {

switch (imageType) {
case PNG:
case APNG:
imageSize = parsePNG(data)
break
case GIF:
Expand Down Expand Up @@ -198,6 +200,7 @@ export async function resolveImageData(
const data = base64ToArrayBuffer(dataString)
switch (imageType) {
case PNG:
case APNG:
imageSize = parsePNG(data)
break
case GIF:
Expand Down Expand Up @@ -283,6 +286,9 @@ function detectContentType(buffer: Uint8Array) {
(b, i) => buffer[i] === b
)
) {
if (detectAPNG(buffer)) {
return APNG
}
return PNG
}
if ([0x47, 0x49, 0x46, 0x38].every((b, i) => buffer[i] === b)) {
Expand All @@ -307,3 +313,19 @@ function detectContentType(buffer: Uint8Array) {
}
return null
}

function detectAPNG(bytes: Uint8Array) {
const dv = new DataView(bytes.buffer)
let type: string,
length: number,
off = 8,
isAPNG = false
while (!isAPNG && type !== 'IEND' && off < bytes.length) {
length = dv.getUint32(off)
const chars = bytes.subarray(off + 4, off + 8)
type = String.fromCharCode(...chars)
isAPNG = type === 'acTL'
off += 12 + length
}
return isAPNG
}

1 comment on commit 7cf0b51

@vercel
Copy link

@vercel vercel bot commented on 7cf0b51 May 24, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.