预览图片并在上传前裁剪

Preview an image and crop it before it's uploaded

本文关键字:裁剪      更新时间:2023-09-26

我有一个图片上传按钮在我的网站。这是我希望它的行为:

  1. 用户点击"选择文件"按钮,选择一个图像。
  2. 图片显示在任何提交之前(使用javascript FileReader API)
  3. 一个裁剪插件应用于该图像,例如:http://www.jqueryrain.com/?BEAlLLl9
  4. 用户选择裁剪区域,点击"提交"。

我需要在2和3之间的步骤上得到帮助。问题使用FileReader API显示图像正确时,他们被选中是,他们得到一个src属性是base64编码。我使用的图像裁剪插件不能正确地找到/初始化/绘制图像,因为它不会识别src=""属性为有效。

如何实现步骤1-4?这在Facebook等主要网站上肯定已经做过了吧?

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. 要显示所选文件的预览,您可以使用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。