2014-06-12 212 views
4

我在我的網站上有一個圖像上傳按鈕。這是我想要它的行爲:在上傳之前預覽圖像並將其裁剪

  1. 用戶單擊「選擇文件」按鈕並選擇一個圖像。
  2. 該圖像示出任何提交(使用JavaScript的FileReader API)
  3. 裁剪插件應用到圖像,例如之前:http://www.jqueryrain.com/?BEAlLLl9
  4. 用戶選擇剪切區域和命中「提交」。

我需要2和3之間的幫助。使用FileReader API在選擇時顯示圖像的問題是,您希望得到一個base64編碼的src屬性。而且我使用的圖像裁剪插件無法正確查找/初始化/繪製圖像,因爲它不會將src=""屬性識別爲有效。

我該如何實現步驟1-4?這確實已經在Facebook等主要網站上完成過了嗎?

回答

3

http://html5.sapnagroup.com/demos/dragDropUploadsCrop/ 此鏈接會引導你想要什麼 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
  1. 要顯示所選文件的預覽,您可以使用createObjectURL方法:

    var windowURL = $window.URL || $window.webkitURL; 
    var imageUrl = windowURL.createObjectURL(imageFile); 
    
  2. 然後當你有像url可以顯示作物選擇的界面。

  3. 當選擇區域時,可以使用畫布裁剪圖像。

    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. 之後,你可以從畫布(https://github.com/blueimp/JavaScript-Canvas-to-Blob),可使用XHR2被上傳到服務器的圖像獲取斑點。