Preview the image and crop it before uploading it.

I have an image upload button on my site. This is how I want him to behave:

  • The user presses the "Select File" button and selects an image.
  • An image is displayed before any view (using the javascript FileReader API)
  • A cropping plugin is applied to this image, for example: http://www.jqueryrain.com/?BEAlLLl9
  • The user selects the cropping area and displays "Submit."

I need help in steps of 2 to 3. The problem with using the FileReader API to display images immediately after selecting them is that it gets the src attribute encoded by base64. And the image cropping plugin that I used cannot correctly find / initialize / draw on the image, since it does not recognize the attribute as src=""valid.

How can I perform step 1-4? Surely this was done earlier on such large sites as Facebook, etc.

+4
source share
2 answers

http://html5.sapnagroup.com/demos/dragDropUploadsCrop/ This link will determine what you want http://html5.sapnagroup.com/2012/08/preview-and-crop-before-upload/

Files with following extensions are only allowed
        allowedExtensions: ['gif','jpg','jpeg','png','txt'],
        showCropTool: 1,
        sizeLimit: 10737418240, // Maximum filesize limit which works without any problems is 30MB. Current limit is set to 10MB = 10 * 1024 * 1024
        params: {
            'uploadedBy': 'Sapnagroup',
            'x1': '0',  // x coordinates of the image
            'y1': '0',      // x coordinates of the image
            'x2': '300',    // x coordinates of the image
            'y2': '150',    // y coordinates of the image
            'cWidth': '300',        // required crop width
            'cHeight': '150',       // required crop heignt
            'oWidth': '800',        // width of the crop preview image
            'oHeight': '600',       // height of the crop preview image
            'rWidth': '300',        // resize width
            'rHeight': '150'        // resize height
        },
+3
  • , createObjectURL:

    var windowURL = $window.URL || $window.webkitURL;
    var imageUrl = windowURL.createObjectURL(imageFile);
    
  • , URL- , .

  • , , .

    function crop(image, x1, y1, x2, y2) {
      var canvas = document.createElement('canvas');
    
      canvas.setAttribute('width', x2 - x1);
      canvas.setAttribute('height', y2 - y1);
    
      var context = canvas.getContext('2d');
      context.drawImage(image, -x1, -y1);
    
      return canvas;
    }
    
  • Blob (https://github.com/blueimp/JavaScript-Canvas-to-Blob), XHR2.

+1

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


All Articles