Php 图像裁剪


Php image cropping

我正在尝试使用"jcrop"库裁剪图像,然后将坐标发送到ajax中的服务器。在 PHP 中对图像进行更改时,我没有得到选定的区域,而是不规则的东西;有时缩放图像,有时裁剪不同的区域。

我将不胜感激任何建议,因为我从两天开始就一直在研究这个问题,慢慢变得疯狂!

谢谢:)

PHP

<?php
  header('Access-Control-Allow-Origin: *');
  //header('Content-Type: image/jpeg');
  $x1 = $_POST['x1'];
  $y1 = $_POST['y1'];
  $x2 = $_POST['x2'];
  $y2 = $_POST['y2'];
  $nw = $_POST['nw']; // new width
  $nh = $_POST['nh']; // new height
  $src = './uploads/hello.jpeg';
  $image = @imagecreatefromjpeg($src) 
        or die('error imagecreatefromjpeg()');
  $width = imagesx($image);
  $height = imagesy($image);
  $cropped = @imagecreatetruecolor($nw, $nh) 
        or die('error imagecreatetruecolor()');
  $result = @imagecopyresampled($cropped, $image, 0, 0, $x1, $y1, $nw, $nh, $width, $height) 
        or die("error imagecopyresampled()");
  // save image
  imagejpeg($cropped, 'test.jpeg', 100);    
?>

jQuery

$(document).ready(function () {
    var x1, y1, x2, y2, nw, nh;
    var width = $('#image').prop('naturalWidth');
    var height = $('#image').prop('naturalHeight');
    function updateCoords(a) {
        x1 = a.x;  y1 = a.y;
        x2 = a.x2; y2 = a.y2;
        nw = a.w;  nh = a.h;
    }
    $('#image').Jcrop({
        trueSize: [width, height],
        onSelect: updateCoords,
        onChange: updateCoords,
        boxWidth: width,
        boxHeight: height
    });
    $('#button').click(function (e) {
        e.preventDefault();
        $.ajax({
           url: 'http://webaddress/server/crop.php',
           type: 'POST',
           crossDomain: true,
           data: {
              x1: x1, y1: y1,
              x2: x2, y2: y2,
              nw: nw, nh: nh
           }
        }).done(function (response) {
              console.log("Server:'n" + response);
        });
    });
});

HTML

<img id="image" src="hello.jpeg" alt="image"/>
<button id="button">Crop</button>

在您的情况下,您使用了不正确的函数。 imagecopyresampled可以更改图像的大小。

对于作物功能,最好的选择是imagecopy

只需尝试更改为此

$result = @imagecopy($cropped, $image, 0, 0, $x1, $y1, $nw, $nh) 
    or die("error imagecopy()");

功能映像复制手册