scale image with ratio and then completes to the canvas size by centering
<?php
function set_image2canvas($file, $new_file, $canvas_width=1200, $canvas_height =1800, $quality=100) {
if (!file_exists( $new_file )) {
list($width, $height, $type, $attr) = getimagesize( $file );
if($width> $height) {
$width_tt=$canvas_width;
$height_tt=round($height/$width*$canvas_width);
$off_y = ceil(( $canvas_height - $height_tt)/2);
$off_x=0;
} else {
$height_tt=$canvas_height;
$width_tt=round($width/$height*$canvas_height);
$off_x=ceil(($canvas_width - $width_tt)/2);
$off_y=0;
}
$thumb=imagecreatefromjpeg( $file );
$thumb_p = imagecreatetruecolor($canvas_width, $canvas_height);
$bg = imagecolorallocate ( $thumb_p, 255, 255, 255 );
imagefill ( $thumb_p, 0, 0, $bg );
imagecopyresampled($thumb_p, $thumb, $off_x, $off_y, 0, 0, $width_tt, $height_tt, $width, $height);
imagejpeg($thumb_p,$new_file,$quality);
}else{ return -1;
}
}
?>