我曾经调整过后端的图片大小。但是现在,为了减少服务器的过载,我想调整前端图像的大小,并通过ajax发送缩小的图像。
在这个网站上,我发现了一个优秀的js功能,可以让你按比例减少它们。它是:
function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) {
ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);
return { width: srcWidth*ratio, height: srcHeight*ratio };
}
但我无法找到如何将其与我的代码相结合。
我目前的代码:
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);
}
});
});
});