Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
99
rated 0 times [  101] [ 2]  / answers: 1 / hits: 16527  / 8 Years ago, wed, february 3, 2016, 12:00:00

I want to avoid uploading big/heavy image files.



I prefer HTML5 FileAPI library for this job.



All other functionality is added (upload, re-order, etc.), so I only need the image-resize function.



CASE:



On the page there is an input for multiple files.



On input change event (when adding files), resize the entered images/files and append them to FormData(), then send the FormData() to PHP script via ajax.



EXAMPLE:



$('input').on('change',function(){
var formData = resizeImages(this.files[0]);
uploadResizedImages(formData);
});

function resizeImages(files){
formData = new FormData();

//For each image, resize it and append to formData
//resize file part missing....
formData.append('files[]',this);//Appending to formData (this = currently iterated file)

return formData;//Return the formData with resized images
}


Anyone?



Thanks


More From » ajax

 Answers
62

In my experience you cannot manipulate the image on the client side then upload the manipulated image in tact via a file input in a form.



The way I have done what you are trying to do in the past involves a few steps.




  1. Select image using a file input

  2. Read the file as a dataURL

  3. Use canvas to manipulate the image as needed

  4. Export the new image as a dataUrl

  5. Use ajax to upload the image to the server as a dataURL

  6. Use server side functions to convert the dataUrl to an image and store



https://jsfiddle.net/0hmhumL1/



function resizeInCanvas(img){
///////// 3-3 manipulate image
var perferedWidth = 2700;
var ratio = perferedWidth / img.width;
var canvas = $(<canvas>)[0];
canvas.width = img.width * ratio;
canvas.height = img.height * ratio;
var ctx = canvas.getContext(2d);
ctx.drawImage(img, 0,0,canvas.width, canvas.height);
//////////4. export as dataUrl
return canvas.toDataURL();
}


When uploading as a dataUrl you increase the size (bandwidth required) of the manipulated image by about 20% so you may not see the savings you are looking for unless you are changing the image size considerably.


[#63459] Monday, February 1, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tammyb

Total Points: 278
Total Questions: 101
Total Answers: 103

Location: Botswana
Member since Sat, Jan 7, 2023
1 Year ago
;