function cropResize(&$gdSource, $newWidth, $newHeight, $mode, $left=false,$top=false,$alpha = false){
// $mode: 1=resize, keep aspect ratio, width & height as max values,
// $mode: 2=resize the relative smallest side, + crop the bigger side if needed, keep aspect ratio
// $mode: 3=resize to desired, NOT keeping aspect ratio
// $mode: 4=just crop, $left and $top needed
// list($oldWidth,$oldHeight) = getimagesize($gdSource); // Get the original dimensions
$oldWidth = imagesx($gdSource);
$oldHeight = imagesy($gdSource);
if ($mode == '1'){// $mode = 1
if (($oldWidth <= $newWidth) && ($oldHeight <= $newHeight)){
return $gdSource;
}
if (($oldWidth <= $newWidth) || ($oldHeight <= $newHeight)){
$finalHeight = $oldHeight;
$finalWidth = $oldWidth;
}
if (($oldHeight > $newHeight) || ($oldWidth > $newWidth)) {
$multiplier = $oldWidth/$oldHeight;
if ($oldHeight/$newHeight > $oldWidth/$newWidth){
$finalHeight = $newHeight;
$finalWidth = $finalHeight*$multiplier;
}
else {
$finalWidth = $newWidth;
$finalHeight = $finalWidth/$multiplier;
}
}
}
if (!$finalHeight){
$finalHeight = $newHeight;
}
if (!$finalWidth){
$finalWidth = $newWidth;
}
if ((($oldWidth/$oldHeight) !== ($newWidth/$newHeight)) && ($mode == '2')){ // $mode = 2
$multiplier = $newWidth/$newHeight;
if (($oldWidth/$oldHeight) < ($newWidth/$newHeight)){
$cropHeight = $oldHeight/$multiplier;
$cropWidth = $oldWidth;
}
elseif (($oldWidth/$oldHeight) > ($newWidth/$newHeight)){
$cropHeight = $oldHeight;
$cropWidth = $oldHeight*$multiplier;
}
}
elseif ($mode == '4'){
$cropHeight = $newHeight;
$cropWidth = $newWidth;
}
else { // $mode = 3 or if can be used by 1 or 2
$cropHeight = $oldHeight;
$cropWidth = $oldWidth;
}
if ($left !== false && $mode == '4'){
$cropLeft = $left;
}
elseif ($cropWidth < $oldWidth && ($mode == '2')){
$cropLeft = ($oldWidth-$cropWidth)/2;
}
else {
$cropLeft = 0;
}
if ($top !== false && $mode == '4'){
$cropTop = $top;
}
elseif ($cropHeight < $oldHeight && ($mode == '2')){
$cropTop = ($oldHeight-$cropHeight)/2;
}
else {
$cropTop = 0;
}
$cropLeft = round($cropLeft);
$cropTop = round($cropTop);
$cropWidth = round($cropWidth);
$cropHeight = round($cropHeight);
$gdOutput = imagecreatetruecolor($finalWidth,$finalHeight);
if ($alpha === true){
$background = imagecolorallocate($gdOutput, 0, 0, 0);
imagecolortransparent($gdOutput, $background); // make the new temp image all transparent
imagealphablending($gdOutput, false); // turn off the alpha blending to keep the alpha channel
imagesavealpha ( $gdOutput, true ); // Save full alpha
}
imagecopyresampled($gdOutput, $gdSource, 0,0, $cropLeft, $cropTop, $finalWidth, $finalHeight, $cropWidth, $cropHeight);
imagedestroy($gdSource);
return $gdOutput;
}