简体   繁体   中英

Preview an image and crop it before it's uploaded

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

  1. A user clicks a "Choose file" button and selects an image.
  2. The image shows before any submission (using javascript FileReader API)
  3. A cropping plugin is applied to that image, for instance: http://www.jqueryrain.com/?BEAlLLl9
  4. The user chooses the cropping area and hits "Submit".

I need help with the step between 2 and 3. The problem using FileReader API to show images right when they are selected is that hey get a src attribute which is base64 encoded. And the image cropping plugin I've used can't properly find/initialize/draw on the image since it won't recognize the src="" attribute as valid.

How can I achieve step 1-4? Surely this has been done before on major sites like Facebook etc?

http://html5.sapnagroup.com/demos/dragDropUploadsCrop/ This link will guide 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
        },
  1. To show preview of selected file you can use createObjectURL method:

     var windowURL = $window.URL || $window.webkitURL; var imageUrl = windowURL.createObjectURL(imageFile); 
  2. Then when you have image url you can display interface for crop selection.

  3. When area to crop where selected you can crop image using canvas.

     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; } 
  4. After that you can get Blob with image from canvas ( https://github.com/blueimp/JavaScript-Canvas-to-Blob ), which can be uploaded to server using XHR2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM