javascript - 图像未正确裁剪或调整大小

标签 javascript php jquery image imagick

我正在尝试构建一个个人资料上传系统。用户将上传图像,在提交之前,他们将有机会裁剪图像。我正在使用cropbox 图像裁剪插件,我还使用jQuery 验证插件。提交后,图像将以完整尺寸裁剪,然后调整为 250 像素 x 250 像素。这是 jsfiddle我所拥有的 HTML 和 jQuery 知识。

HTML

<form class="avatar_form" action="" method="POST" enctype="multipart/form-data">
  <input id="avatar" style="display: block; margin-top: 20px" type="file" name="avatar">
  <input type="hidden" name="width">
  <input type="hidden" name="height">
  <input type="hidden" name="yValue">
  <input type="hidden" name="xValue">

  <div id="stage"></div>
  <input id="upload-btn" type="submit" value="Update profile picture" name="upload">
</form>

jQuery

$(".avatar_form").validate({
  errorElement: 'div',
  rules: {

    avatar: {
      required: true,
      extension: "jpg|png|jpeg|JPG|PNG|JPEG",
      filesize: 100000000,
      minImageSize: {
        width: 250,
        height: 250
      }
    },
  },

  messages: {


    avatar: {
      required: "You have to provide an image.",
      extension: "We only accept .jpg and .png images.",
      filesize: "Your image size should not exceed 100KB",
      minImageSize: "Your image must be at least 250px by 250px."

    },
  },

});

var $form = $('.avatar_form'),
  $upload_btn = $form.find('upload-btn');
$form.find('#avatar').change(function() {
  var $avatar = $(this),
    $imgBox = $("#stage");

  $avatar.removeData('imageSize');
  $imgBox.hide().empty();

  var file = this.files[0];

  if (file.type.match(/image\/.*/)) {
    $upload_btn.attr('disabled', true);

    var reader = new FileReader();

    reader.onload = function() {
      var $img = $('<img />').attr({
        src: reader.result
      });

      $img.on('load', function() {
        $imgBox.append($img).show();

        $avatar.data('imageSize', {
          width: $img.width(),
          height: $img.height()
        });

        $img.css({
          display: "none"
        });

        $upload_btn.attr('disabled', false);

        validator.element($avatar);
      });
    }

    reader.readAsDataURL(file);
  } else {
    validator.element($avatar);
  }
});



$(function() {

  $("#avatar").on('change', function() {
    var file = this.files[0];
    var reader = new FileReader();
    reader.onload = function() {
      var $img = $('<img />').attr({
        src: reader.result
      });

      $img.on('load', function() {
        $img.cropbox({
          width: 250,
          height: 250
        }).on('cropbox', function(event, results, img) {
          $(".width").val(results.cropW);
          $(".height").val(results.cropH);
          $(".yvalue").val(results.cropY);
          $(".xvalue").val(results.cropX);
        });
      });

      $('#stage').append($img);

    };
    reader.readAsDataURL(file);
  });
});

$.validator.addMethod('filesize', function(value, element, param) {
  return this.optional(element) || (element.files[0].size <= param)
}, 'File size must be less than {0}');

$.validator.addMethod('minImageSize', function(value, element, minSize) {
  var imageSize = $(element).data('imageSize');
  return (imageSize) && (imageSize.width >= minSize.width) && (imageSize.height >= minSize.height);
}, function(minSize, element) {
  return ($(element).data('imageSize')) ? ("Your image's size must be at least " + minSize.width + "px by " + minSize.height + "px") : "Selected file is not an image.";
});

PHP

if(isset($_FILES["avatar"], $_POST["width"], $_POST["height"], $_POST["xValue"], $_POST["yValue"]))
            {
                $name = $_FILES["avatar"]["name"];

                $temp_name = $_FILES["avatar"]["tmp_name"];


                            $nameExt = explode('.',$name);
                            $nameExtension = $nameExt[1];

                            $name = $_SESSION["id"] . "." . $nameExtension;
                            $target_avatar_file = $_SERVER['DOCUMENT_ROOT'] . "/profiles/images/avatars/$name";


                                    $xValue = $_POST["xValue"];
                                    $yValue = $_POST["yValue"];
                                    $image = new Imagick($temp_name);
                                    $image->cropImage($_POST["width"], $_POST["height"], $xValue, $yValue);
                                        $image->resizeImage(250,250, imagick::FILTER_LANCZOS, 1, true);

                                        $image->writeImage($target_avatar_file);
                                        $username = $_SESSION["Username"];
                $query_file = "/profiles/images/avatars/$name";
                $db->query("UPDATE Users SET image = '$query_file' WHERE Username = '$username'");
            }

jQuery 验证部分工作正常,但 PHP 部分工作不正常。用户提交图像后,它将被裁剪、调整大小,然后移动到我的服务器。将文件移动到服务器可以正常工作,但裁剪图像和调整大小无法正常工作。当我上传图像时,图像大小会调整为 250 像素 x 167 像素,并且由于某种原因无法正确裁剪。我做错了什么?

最佳答案

这一行:

$image->resizeImage(250,250, imagick::FILTER_LANCZOS, 1, true);

...似乎是多余的,并且它可能会导致按比例调整原始图像的大小。这可以解释为什么宽度正确但高度不正确(对于高度大于宽度的图像,您可能会看到相反的情况)。

在我看来,您只需要 $image->cropImage(...) 调用。

更新:

Imagick::cropImage function获取裁剪区域的宽度和高度以及左上角的 x/y。您传递的是完整图像的宽度/高度,而不是裁剪矩形,因此取决于您的xValueyValue也就是说,您实际上是在选择超出图像 Canvas 边界的裁剪矩形。

关于javascript - 图像未正确裁剪或调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38580131/

相关文章:

javascript - 具有巨大内联样式的网站

php - 需要合并mysql表中的两列日期和时间并找出与当前日期和时间的差异

javascript - 如何从 ASP.NET 检索 JSONdata 并将其发送到 jQuery? (实现全日历)

jquery 和 xhr.abort

javascript - 从粘贴的文本中删除背景颜色所见即所得

javascript - 使用 Javascript 将 blob 转换为 .doc、.docx、.xls 或 .txt 以在浏览器中查看而无需下载

javascript - jQuery.data() 和 .data() 之间的区别?

JavaScript "or"- PHP 中的功能

PHP 表单无法提交

javascript - 下载数据时,JqueryUI 如何读取 jquery 请求上的数据?