Wrote a function for sanitising user uploaded images. It saves the native image in size roughly 800x600 so it still fits on most screens when opened, makes a desired size thumbnail and turns all images into high quality jpegs for smaller bandwidth use.
Thumbnails are made in a similar way a designer would make them in photoshop, first resize the most troublesome dimension to desired size, then crop the rest out so the image retains proportions and most of it ends up in the thumbnail.
<?php
function processImage( $image, $imageId, $thumbWidth, $thumbHeight )
{
$type = $image[ 'type' ];
$galleryPath = 'images/collection/';
if ( strpos( $type, 'image/' ) === FALSE )
{ return FALSE;
}
$type = str_replace( 'image/', '', $type );
$createFunc = 'imagecreatefrom' . $type;
$im = $createFunc( $image[ 'tmp_name' ] );
$size = getimagesize( $image[ 'tmp_name' ] );
$w = $size[ 0 ];
$h = $size[ 1 ];
if ( $w > 800 || $h > 600 )
{ if ( $w > 800 )
{
$nw = 800;
$nh = ceil( $nw*($h/$w) );
}elseif( $h > 600 )
{
$nh = 600;
$nw = ceil( $nh*($w/$h) );
}
$im2 = imagecreatetruecolor( $nw, $nh );
imagecopyresampled( $im2, $im, 0, 0, 0, 0, $nw, $nh, $w, $h );
imagedestroy( $im );
$im = $im2;
$w = $nw;
$h = $nh;
}
$tw = $thumbWidth;
$th = $thumbHeight;
$imT = imagecreatetruecolor( $tw, $th );
if ( $tw/$th > $th/$tw )
{ $tmph = $h*($tw/$w);
$temp = imagecreatetruecolor( $tw, $tmph );
imagecopyresampled( $temp, $im, 0, 0, 0, 0, $tw, $tmph, $w, $h ); imagecopyresampled( $imT, $temp, 0, 0, 0, $tmph/2-$th/2, $tw, $th, $tw, $th ); imagedestroy( $temp );
}else
{ $tmpw = $w*($th/$h );
$imT = imagecreatetruecolor( $tmpw, $th );
imagecopyresampled( $imT, $im, 0, 0, 0, 0, $tmpw, $h, $w, $h ); imagecopyresampled( $imT, $temp, 0, 0, $tmpw/2-$tw/2, 0, $tw, $th, $tw, $th ); imagedestroy( $temp );
}
imagejpeg( $im, $galleryPath . $imgid . '.jpg', 100 );
imagejpeg( $imT, $galleryPath . $imgid . '_thumb.jpg', 100 );
}
?>