简体   繁体   中英

Cropping with Jcrop and PHP GD creates black JPEG

I'm working on an image Upload/Crop feature, utilising Jcrop . The first part works fine, but implementing the Crop is causing headaches. I've looked at the following questions , and none seem completely relevant to my problem.

My form that creates the upload:

<img src="uploads/<?=$image_name?>" id="crop-me">
<form action="complete.php" method="post">
    <input type="hidden" name="image_name" value="<?=$image_name?>">
    <input type="hidden" name="x" id="x">
    <input type="hidden" name="y" id="y">
    <input type="hidden" name="x2" id="x2">
    <input type="hidden" name="y2" id="y2">
    <input type="hidden" name="w" id="w">
    <input type="hidden" name="h" id="h">
    <div class="form-group text-right">
        <button type="submit" class="btn btn-primary">Crop</button>
    </div>
</form>

My Jcrop javascript:

$(document).ready(function() {
    $('#crop-me').Jcrop({
        aspectRatio: 130 / 170, // 0.7647
        minSize: [130, 170],
        setSelect: [260, 340, 0, 0],
        onChange: showCoords,
        onSelect: showCoords
    });
    function showCoords(c) {
        $("#x").val(c.x);
        $("#y").val(c.y);
        $("#x2").val(c.x2);
        $("#y2").val(c.y2);
        $("#w").val(c.w);
        $("#h").val(c.h);
    }
});

And finally, complete.php which does the image generation:

<?php

$targ_w = 130;
$targ_h = 170;
$jpeg_quality = 100;

$src = 'uploads' . $_POST['image_name'];
$img_r = imagecreatefromjpeg($src);
$dst_r = imagecreatetruecolor($targ_w, $targ_h);

imagecopyresampled($dst_r, $img_r, 0, 0, $_POST['x'], $_POST['y'], $targ_w, $targ_h, $_POST['w'], $_POST['h']);

header('Content-type: image/jpeg');
imagejpeg($dst_r, null, $jpeg_quality);

?>

I do get an image on complete.php , at 130x170 dimensions, but it's completely black. I think it might be something to do with an aspect ratio calculation/misalignment (the code I am using is a direct rip from Jcrop's tutorial/manual , but with different widths and heights), but I'm really not sure.

Can someone see where I'm going wrong?

Note: I've checked, and the server is definitely running the GD extension, v2.x

As pointed out by @BloodyKnuckles , there was a typo in this line:

$src = 'uploads' . $_POST['image_name'];

A / was missing at the end of the uploads folder name, and should have read:

$src = 'uploads/' . $_POST['image_name'];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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