Skip to content

Instantly share code, notes, and snippets.

@pedropalhari
Created October 30, 2020 12:51
Show Gist options
  • Save pedropalhari/68f62cd957b8a87d63a6983fe4e913fa to your computer and use it in GitHub Desktop.
Save pedropalhari/68f62cd957b8a87d63a6983fe4e913fa to your computer and use it in GitHub Desktop.
Get blob from <img /> using Canvas. In that way you can append it to a FormData and make a POST with it.
//let img = document.querySelector("img");
async function imgSourceToBlob(img) {
let canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
let ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
let imageBlob = await new Promise((resolve) => {
canvas.toBlob((blob) => resolve(blob));
});
return imageBlob;
}
/**
* let body = new FormData();
* let blob = await imgSourceToBlob(img);
* body.append(
* 'file',
* new File([blob], `${Date.now()}_${user._id}_${index}`, {
* type: blob.type,
* });
* ...
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment