在上传之前预览并裁剪图片

4
我网站上有一个图片上传按钮,我希望它的功能如下:
  1. 用户单击“选择文件”按钮并选择一张图片。
  2. 使用JavaScript FileReader API在提交之前显示该图像。
  3. 应用裁剪插件到该图像,例如:http://www.jqueryrain.com/?BEAlLLl9
  4. 用户选择裁剪区域并单击“提交”。
我需要帮助解决步骤2和步骤3之间的问题。使用FileReader API在选择图片时立即显示图像的问题在于,它们具有base64编码的src属性。我使用的图片裁剪插件无法正确找到/初始化/绘制图像,因为它不会将src = ""属性识别为有效。
我如何实现步骤1-4?毫无疑问,这已经在Facebook等主要站点上完成了吧?
2个回答

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. 之后,您可以从画布中获取带有图像的Blob(https://github.com/blueimp/JavaScript-Canvas-to-Blob),并使用XHR2将其上传到服务器。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接