Skip to content

Instantly share code, notes, and snippets.

@erkobridee
Created January 23, 2019 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erkobridee/08a702db43690a1e015a2d2eefcaa7b6 to your computer and use it in GitHub Desktop.
Save erkobridee/08a702db43690a1e015a2d2eefcaa7b6 to your computer and use it in GitHub Desktop.
example of how read an image from the server as a binary one and parse it to its base64 string
const readImageAsDataURL = async (imageBlob: Blob): Promise<string> => {
// https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
const imageReader = new FileReader();
return new Promise<string>(resolve => {
const load = () => {
imageReader.removeEventListener('load', load);
resolve(imageReader.result as string);
};
imageReader.addEventListener('load', load, false);
imageReader.readAsDataURL(imageBlob);
});
};
const requestImage = async (imageUrl: string): Promise<string> => {
const MimeType = 'image/jpg, image/png';
const headers = {
Accept: MimeType,
['Content-Type']: MimeType
};
try {
const response = await fetch(`https://cors-anywhere.herokuapp.com/${imageUrl}`, {
method: 'GET',
headers
});
if (!response.ok) {
throw response;
}
let output = '';
try {
const blob = await response.blob();
output = await readImageAsDataURL(blob);
} catch (e) {}
return output;
} catch (error) {
throw error;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment