Here's a function I use to "capture" an uploaded image, create a thumbnail (properly resized.. non distorted) and save both to a database... now, before anyone says anything, I store them in a DB because my client SPECIFICALLY requested it... 🙂
Anyway, here's the proggie.
<?php
// array[0]=width (Of Thumbnail)
// array[1]=height (Of Thumbnail)
include ("global.php");
MYSQL_CONNECT("localhost","secret","anothersecret");
mysql_select_db("eba");
$dat = fopen("$p_data", "rb");
$data = fread($dat, filesize($p_data));
$im = ImageCreateFromString($data);
$imagemax[0]=200;
$imagemax[1]=150;
$imagedim[0]=ImageSX($im);
$imagedim[1]=ImageSY($im);
if (ceil($imagedim[0]/4) > ceil($imagedim[1]/3))
{
$x=0;
$y=1;
}
else
{
$x=1;
$y=0;
}
$imageprop=($imagemax[$x]*100)/$imagedim[$x];
$imagesize[$y]=($imagedim[$y]*$imageprop)/100 ;
$imagedim[$x]=$imagemax[$x];
$imagedim[$y]=ceil($imagesize[$y]);
$newimagedim[$x]=$imagedim[$x];
$newimagedim[$y]=$imagedim[$y];
$dst_img=@imagecreate($newimagedim[0],$newimagedim[1]);
$src_img=@imagecreatefromstring($data);
ImageCopyResampleBicubic($dst_img,$src_img,0,0,0,0,$newimagedim[0],$newimagedim[1],ImageSX($src_img),ImageSY($src_img));
$filler_img=@imagecreate($imagemax[0],$imagemax[1]);
$adj_w=($imagemax[0]/2)-ceil($newimagedim[0]/2);
$adj_h=($imagemax[1]/2)-ceil($newimagedim[1]/2);
@imagecopy($filler_img, $dst_img, $adj_w, $adj_h, 0, 0, $newimagedim[0], $newimagedim[1]);
ob_start();
imagejpeg($filler_img);
$myimage=ob_get_contents();
ob_end_clean();
$data = addslashes($data);
$dst_img = addslashes($myimage);
// Check For Moderation Bypass
if ($bypassmod=="yes")
{
$moderated=1;
}
else
{
$moderated=0;
}
$result=MYSQL_QUERY("INSERT INTO pictures (PicModerated,PicData,PicThumbnail,PicDescription,PicCategory1) VALUES ($moderated,'$data','$dst_img','$p_desc','$cat')") or die("Error inserting record");
MYSQL_CLOSE();
header("Location: [url]http://myclientshost[/url]");
?>
If you look closely, you'll notice that this my thumbnails are 200x150 (a 4x3 aspect ratio). This script determines whether the image needs horizontal or vertical "padding" and resizes appropriately.
By all means, post any questions.. Hope this helps and sorry for the lack of comments in the script. I'm kinda bad about that sometimes 😉