简体   繁体   English

图像无法正确裁剪或调整大小

[英]Image not cropping or resizing correctly

I am trying to build a profile upload system. 我正在尝试建立个人资料上传系统。 The user will upload an image, and right before they submit it, they'll have the opportunity to crop the image. 用户将上传图像,并且在提交图像之前,他们将有机会裁剪图像。 I am using the cropbox image crop plugin, I'm also using jQuery validation plugin. 我正在使用cropbox图像裁剪插件,也在使用jQuery验证插件。 Upon submission, the image will be cropped at full size, and then resized to 250px by 250px. 提交后,图像将被全尺寸裁剪,然后将尺寸调整为250px x 250px。 Here's a jsfiddle of what I have HTML and jQuery wise. 这里有一个的jsfiddle的我有什么HTML和jQuery明智的。

HTML 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 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 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'");
            }

The jQuery validation part works correctly, but what doesn't is the PHP part. jQuery验证部分可以正常工作,但PHP部分不是。 Once the user submits the image, it'll be cropped, resized, and then moved to my server. 用户提交图像后,将对其进行裁剪,调整大小,然后移至我的服务器。 Moving the file to the server works, but cropping the image and resizing doesn't work correctly. 将文件移动到服务器上是可行的,但是裁剪图像和调整大小无法正常工作。 When I upload an image, the image gets resized to 250px by 167px and doesn't get cropped properly for some reason. 当我上传图片时,图片大小调整为250px x 167px,由于某种原因无法正确裁剪。 What am I doing wrong? 我究竟做错了什么?

This line: 这行:

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

...seems to be redundant, and it may be causing a proportional resize of the original image. ...似乎是多余的,并且可能会导致按比例调整原始图像的大小。 That would explain why the width is correct but not the height (for an image that is taller than it is wide, you'd probably see the inverse). 这可以解释为什么宽度正确而不是高度正确(对于高于宽度的图像,您可能会看到相反的结果)。

It seems to me like you just need the $image->cropImage(...) call. 在我看来,您只需要$image->cropImage(...)调用。

Update : 更新

The Imagick::cropImage function takes the width and height of the crop region and the x/y of the top-left corner. Imagick :: cropImage函数获取裁剪区域的宽度和高度以及左上角的x / y。 What you're passing instead is the width/height of the full image , not the crop rectangle, so depending on what your xValue and yValue is, you're essentially selecting a crop rectangle that's beyond the boundaries of the image canvas. 相反,您传递的是整个图像的宽度/高度,而不是裁剪矩形,因此,根据xValueyValue的不同,您实际上选择的是超出图像画布边界的裁剪矩形。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM