1

I've added a cropping feature to a social network CMS written in PHP called Sngine. I added a jquery plugin so users can select the area of the image that they want. I'm using imagecopyresampled to select the desired coordinates of the image, however something is going wrong and it doesn't work as expected, a lot of image is not copied over and the final output still retains the black background.

Below is the original image Original image

This is the final output

Final output

I'm really not sure what i'm doing wrong here, a lot of tutorials use the same algorithm to get cropping done. The coordinates are being passed correctly from the crop plugin to the php script.

Below is my code

    <?php
/**
 * ajax -> data -> report
 *
 * @package Sngine
 * @author Zamblek
 */

// fetch bootstrap
require('../../../bootstrap.php');

// fetch image class
require('../../class-image.php');
// check AJAX Request
is_ajax();

// user access

user_access(true);
try {
    $x = $_POST['crop']['x'];
    $y = $_POST['crop']['y'];
    $x2 = $_POST['crop']['x2'];
    $y2 = $_POST['crop']['y2'];
    $width = $_POST['crop']['w'];
    $height = $_POST['crop']['h'];    

    $file_path = $_POST['crop_file'];
    $file_path = $system['uploads_directory'].'/'.$file_path;
    $file_path = '../../../'.$file_path;

    $image = new Image($file_path);
    $type = $image->get_type();

    //crop and resize image
    $newImage = imagecreatetruecolor($width,$height);

    switch($type) {
        case "image/gif":
            $source = imagecreatefromgif($file_path);
            break;
        case "image/pjpeg":
        case "image/jpeg":
        case "image/jpg":
            $source = imagecreatefromjpeg($file_path);
            break;
        case "image/png":
        case "image/x-png":
            $source = imagecreatefrompng($file_path);
            break;
    }
    $src_w = imagesx($source);
    $src_h = imagesy($source);


    //imagecopy($newImage,$source,0,0,$x,$y,$width,$height);
    imagecopyresampled($newImage,$source,0,0,$x,$y,$width,$height,$src_w,$src_h);



    switch($type) {
        case "image/gif":
            imagegif($newImage,$file_path);
            break;
        case "image/pjpeg":
        case "image/jpeg":
        case "image/jpg":
            imagejpeg($newImage,$file_path,90);
            break;
        case "image/png":
        case "image/x-png":
            imagepng($newImage,$file_path);
            break;
    }
    imagedestroy($newImage);
    return_json(['file' => $_POST['crop_file']]);

} catch (Exception $e){
    modal(ERROR, __("Error"), $e->getMessage());
}
Haider Ali
  • 918
  • 2
  • 9
  • 26

0 Answers0