Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 913
slier Avatar asked Dec 24 '12 21:12

slier


2 Answers

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 100x100 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

like image 80
goat Avatar answered Sep 22 '22 14:09

goat


For this, I'd use jCrop. Make sure you have access to ImageMagick and/or GD on your system--you'll most likely need that for processing.

EDIT (Oct 2, 2021) - The original link/library looks to be abandoned. I haven't tried this yet but it looks like it will work: https://jcrop.com/

like image 23
jbnunn Avatar answered Sep 21 '22 14:09

jbnunn