簡體   English   中英

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()");

功能映像復印手冊

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM