Last active
August 4, 2019 17:14
-
-
Save bittu/ff95ed97ae08779167e1fc2213e5344c to your computer and use it in GitHub Desktop.
Javascript Web Workers to process images to base64 data url without canvas using ES2015 Promises
This file contains hidden or 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
let imgs = ['image1.jpg', 'image2.jpg'] | |
let convertedImages = []; | |
let worker = new Worker('worker.js'); | |
worker.addEventListener('message', function(event) { | |
convertedImages = event.data; | |
}) |
This file contains hidden or 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
self.addEventListener('message', function(event) { | |
processImages(event.data).then(function(data) { | |
self.postMessage(data); | |
}) | |
}) | |
function processImages(images) { | |
function processImage(img) { | |
return new Promise(function(resolve, reject) { | |
toDataUrl(img, function(dataUrl) { | |
resolve(dataUrl) | |
}) | |
}) | |
} | |
let promises = []; | |
images.forEach(function(v) { | |
promises.push(v) | |
}) | |
return Promise.all(promises); | |
} | |
function toDataUrl(src, callback) { | |
var xhr = new XMLHttpRequest(); | |
xhr.responseType = 'blob'; | |
xhr.onload = onLoadOfImg; | |
xhr.onerror = onErrorOfImg; | |
xhr.open('GET', src, true); | |
xhr.send(); | |
function onLoadOfImg(rsp) { | |
console.log(rsp.target.status) | |
console.log(rsp); | |
if(rsp.target.status === 200) { | |
var reader = new FileReaderSync(); | |
var blobdata = reader.readAsDataURL(rsp.target.response); | |
console.log(blobdata); | |
callback(blobdata) | |
} else { | |
callback(''); | |
} | |
}; | |
function onErrorOfImg() { | |
callback(''); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Correction:
promises.push(processImage(v))