I have an image processing javascript. Through a file input with an id 'image_input' user can choose to upload an unlimited number of images. When an user uploads images, my jQuery code below catches them and calls my image processing code for each image.
$('#image_input').change(function() {
var input = $(this);
image_count = input[0].files.length;
for (var i = 0; i < image_count; i++) {
Uploader.processImage(input[0].files[i]);
}
});
The process image function creates a new HTML img element and loads the user uploaded image into it. The script waits until the image is loaded and then it converts it into a suitable format and size. Finally, the image is saved into an array: Uploader.images.
Uploader.processImage = function(image) {
var image_element = document.createElement('img');
var image_url = window.URL.createObjectURL(image);
image_element.onload = function() {
image_data = convert(this);
Uploader.images.push(dataUriToBlob(image_data));
}
image_element.src = image_url;
}
I want the images to be stored in the array in the order they were uploaded. The problem is that the onload function is asynchronous, which means that I cannot control in which order the images are saved. For instance, I choose to upload 3 images. Image 1 and image 2 are each 10MB of size but image 3 is only 300 KB. Therefore, conversion of the image 3 is finished first and the final order of the images in the array is 3, 1, 2 (or 3, 2, 1).
How can I synchronize the execution of processImage so that the next image is processed only when the conversion of the previous one is finished?
Aucun commentaire:
Enregistrer un commentaire