I used to resize the images on the back-end. But now, to decrease the overload of my server, I want to resize the images on the front-end and send by ajax the images reduced.
In this site I found an excellent js function that allow you to reduce they proportionally. It is:
function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) {
ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);
return { width: srcWidth*ratio, height: srcHeight*ratio };
}
But I can't find how to couple it with my code.
The code that I have at the moment:
HTML:
<form method="post" id="formimages" enctype="multipart/form-data">
<strong> Upload image:</strong> <br></br>
<input type="file" id="file" name="file[]" multiple>
<button class="btn-primary" type="button" id="btn">Upload image</button>
</form>
<div id="preview">
</div>
<div id="response">
</div>
JS:
$(function () {
$('#file').on("change", function () {
//Clear preview
$('#preview').html('');
var images = document.getElementById('file').files;
var browser = window.URL || window.webkitURL;
//Iterate the files:
for (x = 0; x < images.length; x++) {
var type = images[x].type;
if (type != 'image/jpeg' && type != 'image/jpg' && type != 'image/png' && type != 'image/gif') {
$("#preview").append("<p style='color: red'> The file isn't an image </p>");
}
else {
//Insert images into preview reducing the dimension:
var object_url = browser.createObjectURL(images[x]);
$("#preview").append("<img src=" + object_url + " width='250' height='250' style='width: 250px; height:auto; '><br><br>")
}
}
});
//Send the form:
$('#btn').on("click", function () {
var formData = new FormData($("#formimages")[0]);
var route = "php/carga/adm_prodimages.php";
$.ajax({
url: route,
type: "POST",
data: formData,
contentType: false,
processData: false,
success: function (info) {
$("#response").html(info);
}
});
});
});