I am trying to replace the uploaded by user image with a smaller one, just before upload.
The concept is to modify the 'src' attribute of the input field with the new resized image src. However, this does not happen. Browser submits the original image.
This is my code:
<input type="file" id="input-file-a" name="image" accept="image/*"/>
<img id="preview"/>
var fileReader = new FileReader();
var filterType = /^(?:image...
fileReader.onload = function (event) {
var image = new Image();
image.src = event.target.result;
var elem_id = 'input-file-a';
image.onload = function () {
var canvas = document.createElement("canvas");
var context = canvas.getContext("2d");
canvas.width = image.width / 4;
canvas.height = image.height / 4;
context.drawImage(image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
document.getElementById('preview').src = canvas.toDataURL(); // <--- This shows the resized preview as expected!
document.getElementById(elem_id).src = canvas.toDataURL(); // <--- this does not work, should it?
};
};
function resizeImage() {
var elem_id = 'input-file-a';
var uploadImage = document.getElementById(elem_id);
if (uploadImage.files.length === 0) {
return;
}
var uploadFile = document.getElementById(elem_id).files[0];
if (!filterType.test(uploadFile.type)) {
alert("Please select a valid image.");
return;
}
fileReader.readAsDataURL(uploadFile);
}
What am I doing wrong?