Trim local image file

I got a form that allows the user to upload an image and crop it. I already understood its flow.

1.User upload image
2.Server processes it and sends it back to the browser
3.User crop it and send to server
4.Server and save it

Is there any other way to achieve this? Perhaps using javascript to upload the image, and then crop it, then send it to the server to process it.
Is there any way?

Edited I want to avoid sending this image to the server to process it.
Perhaps upload the file using FileReader ..
I was not lucky with the search on the Internet.

+4
source share
2 answers

You can use FileReader + Canvas to read a local file and then trim it without sending it to the server.

Here is a demo showing how to do this.

 <form><input type="file" id=f></form> <canvas id=c width="600" height="600"></canvas> <script> var f = document.getElementById('f'); var canvas = document.getElementById('c'); var context = canvas.getContext('2d'); f.onchange = function() { var file = this.files[0]; var reader = new FileReader(); reader.onload = function(evt) { var img = new Image(); img.onload = function() { context.drawImage(this, 0, 0, 100, 100, 0, 0, 100, 100); var pngUrl = canvas.toDataURL(); //alert(pngUrl); // send this url to server to save the image } img.src = evt.target.result; } reader.readAsDataURL(file); } </script> 

What else you need to do is use the jquery jcrop plugin so that the user can select the cropping area, because in this demo I just hardcoded the crop of the top left 100x100 pixels.

It looks like you will want to use jcrops onSelect to get the beginning + width + height of the cropping area and feed these values ​​into context.drawImage

hope you can handle the rest, good luck

+3
source

For this I use jCrop . Make sure you have access to ImageMagick and / or GD on your system - you will most likely need to process it.

+1
source

All Articles