Skip to content

Instantly share code, notes, and snippets.

@masahirompp
Last active October 8, 2017 04:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save masahirompp/801e5e67da7760f3f42f07e2d32af168 to your computer and use it in GitHub Desktop.
Save masahirompp/801e5e67da7760f3f42f07e2d32af168 to your computer and use it in GitHub Desktop.
image file to DataUri, DataUri(or image src) to ImageData
export function imageFileToDataUri (file: File) {
return new Promise<string>(done => {
const reader = new FileReader()
reader.onloadend = () => done(reader.result)
reader.readAsDataURL(file)
})
}
export function imageSrcToImageData (imageSrc: string) {
return new Promise<ImageData>(resolve => {
const $img = new Image()
$img.onload = () => {
const $canvas = document.createElement('canvas')
$canvas.width = $img.naturalWidth
$canvas.height = $img.naturalHeight
const ctx = $canvas.getContext('2d') as CanvasRenderingContext2D
ctx.drawImage($img, 0, 0)
const data = ctx.getImageData(0, 0, $canvas.width, $canvas.height)
resolve(data)
}
$img.src = imageSrc
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment