裁剪图像并使用 PHP 上传

3
我有一个裁剪图片的脚本。当用户点击保存按钮时,该脚本如何上传裁剪后的图像?我如何让PHP处理裁剪后的图像并上传到服务器?
文档在这里 github - cropperjs

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Cropper.js</title>
  <!-- <link rel="stylesheet" href="dist/cropper.css"> -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/0.8.1/cropper.css" />
  
  <style>
    .container {
      max-width: 640px;
      margin: 20px auto;
    }

    img {
      max-width: 100%;
    }
  </style>
</head>
<body>

  <div class="container">
    <h1>Cropper with a range of aspect ratio</h1>
 
    <div>
      <img id="image" src="https://fengyuanchen.github.io/cropperjs/images/picture.jpg" alt="Picture">
    </div>
 <button onclick="cropper.getCroppedCanvas()">Save</button>
  </div>

  <!-- <script src="dist/cropper.js"></script> -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/0.8.1/cropper.js"></script>
  <script>
    window.addEventListener('DOMContentLoaded', function () {
      var image = document.querySelector('#image');
      var minAspectRatio = 1.0;
      var maxAspectRatio = 1.0;
      var cropper = new Cropper(image, {
        ready: function () {
          var cropper = this.cropper;
          var containerData = cropper.getContainerData();
          var cropBoxData = cropper.getCropBoxData();
          var aspectRatio = cropBoxData.width / cropBoxData.height;
          var newCropBoxWidth;

          if (aspectRatio < minAspectRatio || aspectRatio > maxAspectRatio) {
            newCropBoxWidth = cropBoxData.height * ((minAspectRatio + maxAspectRatio) / 2);

            cropper.setCropBoxData({
              left: (containerData.width - newCropBoxWidth) / 2,
              width: newCropBoxWidth
            });
          }
        },
        cropmove: function () {
          var cropper = this.cropper;
          var cropBoxData = cropper.getCropBoxData();
          var aspectRatio = cropBoxData.width / cropBoxData.height;

          if (aspectRatio < minAspectRatio) {
            cropper.setCropBoxData({
              width: cropBoxData.height * minAspectRatio
            });
          } else if (aspectRatio > maxAspectRatio) {
            cropper.setCropBoxData({
              width: cropBoxData.height * maxAspectRatio
            });
          }
        }
      });
    });
  </script>
  <!-- FULL DOCUMENTATION ON https://github.com/fengyuanchen/cropperjs -->
  <!-- My question is: How do i get the cropped image and upload via php ? -->
 
</body>
</html>


请查看这个链接。我已经遇到过这个问题并进行了测试。http://stackoverflow.com/questions/11132841/php-jquery-image-crop-and-upload/23787221#23787221 - Shafiqul Islam
这是另一个脚本,我想使用这个脚本 https://github.com/fengyuanchen/cropperjs 来完成。 - Otávio Barreto
1个回答

3
当点击保存按钮时如何裁剪和上传图片?如何使php获取裁剪后的图片并上传到服务器?
说明文档中,方法getCroppedCanvas()的描述提到了上传裁剪后的图片。

After then, you can display the canvas as an image directly, or use HTMLCanvasElement.toDataURL to get a Data URL, or use HTMLCanvasElement.toBlob to get a blob and upload it to server with FormData if the browser supports these APIs.1

cropper.getCroppedCanvas().toBlob(function (blob) {
  var formData = new FormData();

  formData.append('croppedImage', blob);

  // Use `jQuery.ajax` method
  $.ajax('/path/to/upload', {
    method: "POST",
    data: formData,
    processData: false,
    contentType: false,
    success: function () {
      console.log('Upload success');
    },
    error: function () {
      console.log('Upload error');
    }
  });
});

对于你的例子,标有保存的按钮引用了cropper,但是它只在DOM加载回调函数(即window.addEventListener('DOMContentLoaded', function () {}))内定义。我建议使用事件委托(参见下面提到的示例plunker),但如果你想引用cropper,它需要在DOM加载回调函数之外声明。

var cropper;
window.addEventListener('DOMContentLoaded', function () {
    //assign cropper:
    cropper = new Cropper(image, { ...

您可以在这个plunker中看到它的实际应用。它利用了一个PHP代码,仅仅需要上传裁剪后的图片并返回base64编码版本(使用base64_encode())。
下面是plunker示例中使用的PHP代码:
<?php
$output = array();

if(isset($_FILES) && is_array($_FILES) && count($_FILES)) {
     $output['FILES'] = $_FILES;

     //this is where the cropped image could be saved on the server
     $output['uploaded'] = base64_encode(file_get_contents($_FILES['croppedImage']['tmp_name']));
}
header('Content-Type: application/json');
echo json_encode($output);

除了仅回显文件的base64编码版本外,可以使用move_uploaded_file()上传该文件,然后返回有关已上传文件的信息(例如文件ID、路径等)。

move_uploaded_file($_FILES['croppedImage']['tmp_name'], '/path/to/save/cropped/image');

1(https://github.com/fengyuanchen/cropperjs#user-content-getcroppedcanvasoptions)


我会做到的! - Otávio Barreto

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