Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
There are two versions of the code, in the first version, it is the picture that is written to the blob (which I am looking for and dropping it into the input)
JavaScript
let File = document.querySelector('input').files[0]
let blobUpload = new Blob([File], {type: 'image/jpg'},)

In the second option, the picture is not written to the blob
JavaScript
let File = new Image()
File.src = "car1.jpg"
let blobUpload = new Blob([File], {type: 'image/jpg'},)


What I have tried:

As I understand it, it does not see img as a file
The question is, how do I record the picture manually - without dragging the file?
Posted
Updated 16-Dec-22 4:53am
v2

1 solution

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:
C#
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:
JavaScript
loadImageAsync("car1.jpg").then(img => imageToBlobAsync(img, "image/jpg")).then(blobUpload => {
    ...
});
Or use an async function[^]:
JavaScript
const uploadImage = async () => {
    const img = await loadImageAsync("car1.jpg");
    const blobUpload = await imageToBlobAsync(img, "image/jpg");
    ...
};
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900