-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimageHelpers.js
66 lines (61 loc) · 1.67 KB
/
imageHelpers.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/**
* @param {string} url
* @return {Promise<{
* base64: string,
* dimension: {
* width: number,
* height: number,
* }
* }>}
*/
export async function fetchImageAsBase64(url) {
return new Promise((resolve, reject) => {
const xhr = new window.XMLHttpRequest();
xhr.onload = function () {
const reader = new window.FileReader();
reader.onloadend = async function () {
const base64 = reader.result.replace('data:image/jpeg;base64,', '');
const dimension = await new Promise((resolve, reject) => {
// read image dimensions
const img = new window.Image();
img.src = url;
img.onload = function () {
resolve({ width: img.width, height: img.height });
};
img.onerror = function () {
reject(new Error('Error fetching image dimensions.'));
};
});
resolve({
base64,
dimension,
});
};
reader.readAsDataURL(xhr.response);
};
xhr.onerror = function () {
reject(new Error('Error fetching image.'));
};
xhr.responseType = 'blob';
xhr.open('GET', url);
xhr.send();
});
}
export async function fetchImageAsUint8Array(url) {
return new Promise((resolve, reject) => {
const xhr = new window.XMLHttpRequest();
xhr.onload = function () {
const reader = new window.FileReader();
reader.onloadend = function () {
resolve(reader.result);
};
reader.readAsArrayBuffer(xhr.response);
};
xhr.onerror = function () {
reject(new Error('Error fetching image.'));
};
xhr.responseType = 'blob';
xhr.open('GET', url);
xhr.send();
});
}