Skip to content

Instantly share code, notes, and snippets.

@CodeWitchBella
Created September 5, 2022 20:10
Show Gist options
  • Save CodeWitchBella/8f89de4c19ecdcf2a002af6b70bfe497 to your computer and use it in GitHub Desktop.
Save CodeWitchBella/8f89de4c19ecdcf2a002af6b70bfe497 to your computer and use it in GitHub Desktop.
Minimal JFIF parser. Note that it does not work for all types of JPEG
// if in browser, just use https://developer.mozilla.org/en-US/docs/Web/API/createImageBitmap
// you probably have to read the pixel data at some point anyway...
function parseImageMeta(image: Uint8Array) {
// https://en.wikipedia.org/wiki/JPEG_File_Interchange_Format
if (jfif.every((value, index) => value < 0 || image[index] === value)) {
const view = new DataView(image.buffer)
let offset = 2
while (true) {
if (view.getUint8(offset) !== 0xff)
throw new Error('Each JFIF section should start with 0xff')
const type = view.getUint8(offset + 1)
if (type === 0 || type === 0xff) throw new Error('Invalid JFIF section')
const size = view.getUint16(offset + 2, false) - 2
if (type === 0xc0 && size >= 5) {
const height = view.getUint16(offset + 5)
const width = view.getUint16(offset + 7)
return { width, height, mime: 'image/jpeg' }
}
offset += 4 + size
}
}
return null
}
// https://en.wikipedia.org/wiki/List_of_file_signatures
// prettier-ignore
const jfif = [
0xff, 0xd8, 0xff, 0xe0,
/* section size: */ -1, -1,
/* JFIF in ASCII: */ 0x4a, 0x46, 0x49, 0x46, 0x00,
/* version 1.x: */ 0x01,
// rest does not matter for detection
]
const hex = '0123456789ABCDEF'
function hexPrint(image: Uint8Array) {
return Array.from(
image,
(v) => '0x' + hex[Math.floor(v / 16)] + hex[v % 16],
).join(', ')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment