Created
January 23, 2019 13:59
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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