<!doctype html> <html> <head> <meta content="text/html; charset=UTF-8" http-equiv="Content-Type" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Image resize before upload jquery</title> <style> body{ margin: 25px; font-size: 1.5rem; } </style> <script type="text/javascript">
const fileReader = new FileReader();
const filterType = /^(?:image\/bmp|image\/cis\-cod|image\/gif|image\/ief|image\/jpeg|image\/jpeg|image\/jpeg|image\/pipeg|image\/png|image\/svg\+xml|image\/tiff|image\/x\-cmu\-raster|image\/x\-cmx|image\/x\-icon|image\/x\-portable\-anymap|image\/x\-portable\-bitmap|image\/x\-portable\-graymap|image\/x\-portable\-pixmap|image\/x\-rgb|image\/x\-xbitmap|image\/x\-xpixmap|image\/x\-xwindowdump)$/i;
fileReader.onload = function (event) {
const image = new Image();
image.onload=function(){
document.getElementById("original-Img").src=image.src;
const canvas=document.createElement("canvas");
const context=canvas.getContext("2d");
const width = 400; // set your width
const scaleFactor = width / image.width;
canvas.width = width;
canvas.height = image.height * scaleFactor;
context.drawImage(image, 0, 0, width, image.height * scaleFactor);
document.getElementById("upload-Preview").src = canvas.toDataURL("image/jpeg");
}
image.src=event.target.result;
};
const loadImageFile = function () {
const uploadImage = document.getElementById("upload-Image");
//check and retuns the length of uploded file.
if (uploadImage.files.length === 0) {
return;
}
//Is Used for validate a valid file.
const uploadFile = document.getElementById("upload-Image").files[0];
if (!filterType.test(uploadFile.type)) {
alert("Please select a valid image.");
return;
}
fileReader.readAsDataURL(uploadFile);
}
</script> </head> <body onload="loadImageFile();"> <form name="uploadForm"> <table> <tbody> <tr> <td> Select Image - <input id="upload-Image" type="file" onchange="loadImageFile();" /> </td> </tr> <tr> <td> Origal Image - <img id="original-Img" style="width:800px;height:100%;" /> </td> </tr> <tr> <td> Compress Image - <img id="upload-Preview" /> </td> </tr> <tr> <td> <br />Developed by - <a href="https://guruchian.blogspot.com/" ratget="_blank"> Wichy P.</a> </td> </tr> </tbody> </table> </form> </body> </html>
Code by - Shinerweb