Rotate and then crop an image using PHP
I am trying to crop an image, but when I do this, it appears as the correct size, but everything is black. I've tried at least a dozen different scripts, but I can't seem to get them to work :(
Oh and the rotation script works fine and all echoes are for testing only and will be removed: D
<?php
$staffID        =   $_POST['u'];
$actCode        =   $_POST['a'];
$tempAvatar     =   $_POST['tempAvatar'];
$x1             =   $_POST['x'];
$y1             =   $_POST['y'];
$wH             =   $_POST['w'];
$scale          =   $_POST['scale'];
$angle          =   $_POST['angle'];
$destFolder     =   "../../../avatars/";
$imagePath      =   "tempAvatars/".$tempAvatar.".jpg";
$imagePathRot   =   "tempAvatars/".$tempAvatar."ROTATED.jpg";
$imagePathCropped=  "tempAvatars/".$tempAvatar."CROPPED.jpg";
echo 'X1: '.$x1.'<br>Y1: '.$y1.'<br>Width/Height: '.$wH.'<br>Angle: '.$angle;
if ($angle != 0) {
    $source = imagecreatefromjpeg($imagePath) or notfound();
    $rotate = imagerotate($source,$angle,0);
    imagejpeg($rotate, $imagePathRot);
    $imagePath  =   $imagePathRot;
}
echo '<br>X2: '.$x2.'<br>Y2: '.$y2;
$targ_w = 300;
$jpeg_quality = 90;
$img_r = imagecreatefromjpeg($imagePath);
$dst_r = ImageCreateTrueColor( $targ_w, $targ_w );
imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],
    $targ_w,$targ_h,$_POST['w'],$_POST['w']);
imagejpeg($dst_r, $imagePathCropped, $jpeg_quality);
echo '<br><img src="'.$imagePathCropped.'">';
?>
      
        
        
        
      
     
+3 
Timothy Richard Elliott 
source
to share
      
1 answer
      
        
        
        
      
    
Your problem is that it $targ_h
      
        
        
        
      
    is undefined, so you are copying "pixels" from pixel "0" from the original image. It is in the correct size because it resolved ImageCreateTrueColor
      
        
        
        
      
    and of course initialized to black. The correct call according to the rest of your code should be:
imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],
    $targ_w,$targ_w,$_POST['w'],$_POST['w']);
      
        
        
        
      
     
+2 
Ioannis Karadimas 
source
to share