Creating a new
Image
and setting its
src
will
not block the script and wait for the image to finish downloading.
You need to wait for the remote image to load, then use a canvas to convert it to
Blob
:
https://javascript.info/blob#image-to-blob[
^]
Create a couple of helper methods:
const loadImageAsync = (url) => new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = () => reject(`Unable to load image ${url}.`);
img.setAttribute("crossorigin", "anonymous");
img.src = url;
});
const imageToBlobAsync = (img, type = "image/png") => new Promise((resolve, reject) => {
const canvas = document.createElement("canvas");
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
const context = canvas.getContext("2d");
context.drawImage(img, 0, 0);
canvas.toBlob(resolve, type);
});
You can then either pass a callback to the methods:
loadImageAsync("car1.jpg").then(img => imageToBlobAsync(img, "image/jpg")).then(blobUpload => {
...
});
Or use
an async
function[
^]:
const uploadImage = async () => {
const img = await loadImageAsync("car1.jpg");
const blobUpload = await imageToBlobAsync(img, "image/jpg");
...
};