Skip to content
Advertisement

Crop local image file

I got a form that allow user to upload image and crop it I already figured out the flow of it

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

Is there any other way to achieve this?
Perhaps using javascript to load the image and then crop it then after that send to server to process it.
Is there a way?

Edited Im looking to avoid sending those image to server to process it.
Probably load the file using FileReader..
I have no luck on googling it

Advertisement

Answer

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

Here’s a demo showing how to do that.

<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 you still need to do is use the jquery jcrop plugin in order to let the user select the cropping area because in this demo I just hard coded a crop of the top left 100×100 pixels.

It looks like you’ll want to use jcrops onSelect event to get the origin + width + height of the cropping area, and feed those values into context.drawImage

hopefully you can handle the rest, good luck

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement