Can I resize an image (client side) in html form before uploading?

I have a standard html input form that includes a field for uploading a file (image).

Unfortunately, I can’t edit the backend php that processes the file, but I need to resize the images to a certain size.

I thought I could remove this trick by resizing images using jquery or alternative methods on the client side of the form before actually submitting it to the PHP form.

Is it possible? Does anyone know a good method?

Thanks!!!

+6
source share
1 answer

You can use the new FileReader so that the user can select an image from his local file system.

You can then use the canvas to resize the image as needed.

enter image description here

This code allows the user to select a local image file.

The image will be reduced to half the size on the client side.

<!doctype html> <html> <head> <meta content="text/html; charset=UTF-8" http-equiv="Content-Type" /> <title>Image preview example</title> <script type="text/javascript"> oFReader = new FileReader(), rFilter = /^(?: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; oFReader.onload = function (oFREvent) { var img=new Image(); img.onload=function(){ document.getElementById("originalImg").src=img.src; var canvas=document.createElement("canvas"); var ctx=canvas.getContext("2d"); canvas.width=img.width/2; canvas.height=img.height/2; ctx.drawImage(img,0,0,img.width,img.height,0,0,canvas.width,canvas.height); document.getElementById("uploadPreview").src = canvas.toDataURL(); } img.src=oFREvent.target.result; }; function loadImageFile() { if (document.getElementById("uploadImage").files.length === 0) { return; } var oFile = document.getElementById("uploadImage").files[0]; if (!rFilter.test(oFile.type)) { alert("You must select a valid image file!"); return; } oFReader.readAsDataURL(oFile); } </script> </head> <body onload="loadImageFile();"> <form name="uploadForm"> <table> <tbody> <tr> <td><img id="originalImg"/></td> <td><img id="uploadPreview"/></td> <td><input id="uploadImage" type="file" name="myPhoto" onchange="loadImageFile();" /></td> </tr> </tbody> </table> </form> </body> </html> 

Modern browsers support FileReader (but for IE you need 10+).

+11
source

Source: https://habr.com/ru/post/949176/


All Articles