This is a tidied up version of a couple of functions I use. First function just makes the image smaller, the second one turns it into a sqaure:
You should be able to modify one of these to do what you need. Both take a max size, which for the first function sets the max width or height, depending on which is biggest. On the second, I work out the smallest dimension, then resize the image, cropping off the excess from the longest dimension.
Code: Select all
function resize_normal($image_type,$file_old,$file_new,$max_size)
{
//
// $image_type should be either:
//
// png, jpg or gif
//
list($width, $height) = getimagesize($file_old);
if($width <= $max_size && $height <= $max_size){
copy($file_old, $file_new);
} else {
if ($width > $height){
$resize_percent = $max_size / $width;
$new_height = $height * $resize_percent;
$new_width = $max_size;
} else {
$resize_percent = $max_size / $height;
$new_height = $max_size;
$new_width = $width * $resize_percent;
}
$temp_image = imagecreatetruecolor($new_width, $new_height);
switch($image_type){
case 'png':
$image = imagecreatefrompng($file_old);
imagecopyresampled($temp_image, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagepng($temp_image, $file_new);
break;
case 'jpg':
$image = imagecreatefromjpeg($file_old);
imagecopyresampled($temp_image, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagejpeg($temp_image, $file_new);
break;
case 'gif':
$image = imagecreatefromgif($file_old);
imagecopyresampled($temp_image, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagegif($temp_image, $file_new);
break;
}
}
}
function resize_square($image_type,$file_old,$file_new,$max_size)
{
//
// $image_type should be either:
//
// png, jpg or gif
//
list($width, $height) = getimagesize($file_old);
if($width <= $max_size && $height <= $max_size){
copy($file_old, $file_new);
} else {
if ($width > $height) {
$src_w = $src_h = $height;
$src_y = 0;
$src_x = round(($width - $height) / 2);
} else {
$src_w = $src_h = $width;
$src_x = 0;
$src_y = round(($height - $width) / 2);
}
$temp_image = imagecreatetruecolor($max_size, $max_size);
switch($image_type){
case 'png':
$image = imagecreatefrompng($file_old);
imagecopyresampled($temp_image, $image, 0, 0, $src_x, $src_y, $max_size, $max_size, $src_w, $src_h);
imagepng($temp_image, $file_new);
break;
case 'jpg':
$image = imagecreatefromjpeg($file_old);
imagecopyresampled($temp_image, $image, 0, 0, $src_x, $src_y, $max_size, $max_size, $src_w, $src_h);
imagejpeg($temp_image, $file_new);
break;
case 'gif':
$image = imagecreatefromgif($file_old);
imagecopyresampled($temp_image, $image, 0, 0, $src_x, $src_y, $max_size, $max_size, $src_w, $src_h);
imagegif($temp_image, $file_new);
break;
}
}
}