Skip to content

Commit f9952f5

Browse files
committed
Add getImageDataFromURL() implementation using fetch
1 parent ec40323 commit f9952f5

File tree

1 file changed

+49
-5
lines changed

1 file changed

+49
-5
lines changed

src/utils/getImageDataFromURL.ts

Lines changed: 49 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,56 @@
1+
/* global fetch */
2+
// TODO: Read data:// URLs
3+
// TODO: Load node polyfill
4+
// TODO: Read from FS
15
import sha1 from 'js-sha1';
26

7+
const ERROR_IMAGE =
8+
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mM8w8DwHwAEOQHNmnaaOAAAAABJRU5ErkJggg==';
9+
10+
const ERROR_RESULT = {
11+
data: ERROR_IMAGE,
12+
sha1: sha1(ERROR_IMAGE),
13+
};
14+
15+
const readBufferFromResponse = async (response: Response): Promise<Buffer> => {
16+
const arrayBuffer = await response.arrayBuffer();
17+
if (Buffer.isBuffer(arrayBuffer)) {
18+
// skpm polyfill returns a Buffer instead of an ArrayBuffer
19+
return arrayBuffer;
20+
}
21+
return Buffer.from(arrayBuffer);
22+
};
23+
24+
const isImage = (buffer: Buffer): boolean => {
25+
const firstByte = buffer[0];
26+
27+
// Check for first byte to see if we have an image.
28+
// 0xFF = JPEG, 0x89 = PNG, 0x47 = GIF, 0x49 = TIFF, 0x4D = TIFF
29+
return (
30+
firstByte === 0xff ||
31+
firstByte === 0x89 ||
32+
firstByte === 0x47 ||
33+
firstByte === 0x49 ||
34+
firstByte === 0x4d
35+
);
36+
};
37+
338
export default async function getImageDataFromURL(
439
url?: string,
5-
): Promise<{ data: string; sha1: string }> {
6-
// FIXME: Mock
7-
console.log(url);
8-
const data =
9-
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mM8w8DwHwAEOQHNmnaaOAAAAABJRU5ErkJggg==';
40+
): Promise<Readonly<{ data: string; sha1: string }>> {
41+
if (!url) {
42+
return ERROR_RESULT;
43+
}
44+
45+
const response = await fetch(url);
46+
if (!response.ok) {
47+
return ERROR_RESULT;
48+
}
49+
50+
const buffer = await readBufferFromResponse(response);
51+
if (!isImage(buffer)) return ERROR_RESULT;
52+
53+
const data = buffer.toString('base64');
1054

1155
return {
1256
data,

0 commit comments

Comments
 (0)