Line data Source code
1 8 : function parseExifData(exifData: Uint8Array) {
2 8 : const isLittleEndian = String.fromCharCode(...exifData.slice(0, 2)) === 'II'
3 :
4 80 : function readInt(
5 : offset: number,
6 : isLittleEndian: boolean,
7 : length: 2 | 4
8 : ): number {
9 80 : const arr = exifData.slice(offset, offset + length)
10 80 : const view = new DataView(arr.buffer, arr.byteOffset, arr.byteLength)
11 80 : return length === 2
12 : ? view.getUint16(0, isLittleEndian)
13 : : view.getUint32(0, isLittleEndian)
14 : }
15 :
16 8 : const ifdOffset = readInt(4, isLittleEndian, 4)
17 :
18 8 : function parseIFD(offset: number): Record<number, string | undefined> {
19 8 : const numEntries = readInt(offset, isLittleEndian, 2)
20 8 : const result: Record<number, string | undefined> = {}
21 :
22 8 : for (let i = 0; i < numEntries; i++) {
23 16 : const entryOffset = offset + 2 + i * 12
24 16 : const tag = readInt(entryOffset, isLittleEndian, 2)
25 16 : const type = readInt(entryOffset + 2, isLittleEndian, 2)
26 16 : const numValues = readInt(entryOffset + 4, isLittleEndian, 4)
27 16 : const valueOffset = readInt(entryOffset + 8, isLittleEndian, 4)
28 :
29 16 : let value
30 16 : if (type === 2) {
31 15 : value = new TextDecoder('utf-8').decode(
32 : exifData.subarray(valueOffset, valueOffset + numValues - 1)
33 : )
34 : }
35 :
36 16 : result[tag] = value
37 : }
38 :
39 8 : return result
40 : }
41 :
42 : const ifdData = parseIFD(ifdOffset)
43 8 : return ifdData
44 : }
45 :
46 11 : export function getFromWebpFile(file: File) {
47 11 : return file
48 : .arrayBuffer()
49 : .then((buffer): Record<string, string> => {
50 11 : const webp = new Uint8Array(buffer)
51 11 : const dataView = new DataView(webp.buffer)
52 :
53 11 : if (
54 : dataView.getUint32(0) !== 0x52494646 ||
55 : dataView.getUint32(8) !== 0x57454250
56 : ) {
57 0 : console.error('Not a valid WEBP file')
58 0 : return {}
59 : }
60 :
61 11 : let offset = 12
62 11 : const txt_chunks: Record<string, string> = {}
63 11 : while (offset < webp.length) {
64 27 : const chunk_length = dataView.getUint32(offset + 4, true)
65 : const chunk_type = String.fromCharCode(
66 : ...webp.slice(offset, offset + 4)
67 : )
68 27 : if (chunk_type === 'EXIF') {
69 8 : let exifOffset = offset + 8
70 8 : let exifLength = chunk_length
71 8 : if (
72 : String.fromCharCode(...webp.slice(exifOffset, exifOffset + 6)) ==
73 : 'Exif\0\0'
74 : ) {
75 1 : exifOffset += 6
76 1 : exifLength -= 6
77 : }
78 8 : const data = parseExifData(
79 : webp.slice(exifOffset, exifOffset + exifLength)
80 : )
81 8 : for (const key in data) {
82 16 : const value = data[Number(key)]
83 16 : if (typeof value === 'string') {
84 15 : const index = value.indexOf(':')
85 15 : txt_chunks[value.slice(0, index)] = value.slice(index + 1)
86 : }
87 : }
88 8 : break
89 : }
90 :
91 19 : offset += 8 + chunk_length + (chunk_length % 2)
92 : }
93 :
94 11 : return txt_chunks
95 : })
96 : .catch((): Record<string, string> => ({}))
97 : }
|