image.ts 1.0 KB

1234567891011121314151617181920212223242526272829
  1. export const dimensions = (data: Uint8Array) => {
  2. if (data[0] === 0x89 && data[1] === 0x50 && data[2] === 0x4e && data[3] === 0x47)
  3. return {
  4. width: readUint32(data, 16),
  5. height: readUint32(data, 20),
  6. }
  7. if (data[0] === 0xff && data[1] === 0xd8) {
  8. for (let offset = 2; offset + 8 < data.length; ) {
  9. if (data[offset] !== 0xff) {
  10. offset++
  11. continue
  12. }
  13. const marker = data[offset + 1]
  14. if (
  15. marker !== undefined &&
  16. [0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf].includes(marker)
  17. )
  18. return {
  19. width: (data[offset + 7] << 8) | data[offset + 8],
  20. height: (data[offset + 5] << 8) | data[offset + 6],
  21. }
  22. offset += 2 + ((data[offset + 2] << 8) | data[offset + 3])
  23. }
  24. }
  25. throw new Error("Unsupported image fixture format")
  26. }
  27. const readUint32 = (data: Uint8Array, offset: number) =>
  28. ((data[offset] << 24) | (data[offset + 1] << 16) | (data[offset + 2] << 8) | data[offset + 3]) >>> 0