1

Is it possible to crop an image on the front end through a browser with JavaScript?

I am able to send an image along with dimensions and coordinates to a server having the backend crop the image.

What I want to do is crop an image through the browser with JavaScript then if need be, send the cropped image to a server.

Aaron
  • 3,195
  • 5
  • 31
  • 49
  • 2
    See those related questions in the sidebar to the right? I count at least four that ask the same question. – j08691 Oct 28 '13 at 18:56

3 Answers3

3

You can do this by loading the image into a Canvas element and then manipulating the Canvas

Basic tutorial here

http://www.w3schools.com/html/html5_canvas.asp

(plenty more available)

splig
  • 371
  • 1
  • 4
  • 11
2

You could use the image as a background for an element and then use background-position: Zpx Ypx; to position the image as you want.

It would not be cropped, but it would look like it is.

Diosney
  • 10,520
  • 15
  • 66
  • 111
Harri
  • 2,692
  • 2
  • 21
  • 25
1

You can try from

http://www.codeforest.net/html5-image-upload-resize-and-crop

function resizeAndUpload(file) {
var reader = new FileReader();
    reader.onloadend = function() {

    var tempImg = new Image();
    tempImg.src = reader.result;
    tempImg.onload = function() {

        var MAX_WIDTH = 400;
        var MAX_HEIGHT = 300;
        var tempW = tempImg.width;
        var tempH = tempImg.height;
        if (tempW > tempH) {
            if (tempW > MAX_WIDTH) {
               tempH *= MAX_WIDTH / tempW;
               tempW = MAX_WIDTH;
            }
        } else {
            if (tempH > MAX_HEIGHT) {
               tempW *= MAX_HEIGHT / tempH;
               tempH = MAX_HEIGHT;
            }
        }

        var canvas = document.createElement('canvas');
        canvas.width = tempW;
        canvas.height = tempH;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(this, 0, 0, tempW, tempH);
        var dataURL = canvas.toDataURL("image/jpeg");

        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(ev){
            document.getElementById('filesInfo').innerHTML = 'Done!';
        };

        xhr.open('POST', 'uploadResized.php', true);
        xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        var data = 'image=' + dataURL;
        xhr.send(data);
      }

   }
   reader.readAsDataURL(file);
}

This code is only for client size resizing. For cropping you can use something like Jcrop.

ʞᴉɯ
  • 5,376
  • 7
  • 52
  • 89