I have created an online photogallery. On it I have a script that runs semi-successfully that uploads a large JPG file (say 640x480 pixels, at around 80% compression), saves this to my webserver, and at the same time generates and saves a new thumbnail file of that photgraph.
THe function should look at the large file, take a square from the centre of the (usually) rectangular source photo, and create a 100x100 pixel thumbnail file at around 80% compression. It does this, but it makes a terribel job of the compression of the jpg, and my files look very muddy and murky.
To see this is action I suggest looking at http://www.cheche.co.nz/home.php which has the most recent thiumbnails. clicking through the thumbnails will show the original images.
the function I use is pasted below:
Code: Select all
<?php
# upload a file to the album.
function uploadFile($title, $subject, $comment, $userfile, $userfile_size, $userfile_type) {
#insert the file into the database...
$query = "INSERT INTO data_photo (date, subject, title, comment) VALUES ('".date("Y-m-d H:i:s")."', '".$subject."', '".$title."', '".$comment."')";
mysql_query($query);
# retrieve the latest id for image naming purposes...
$newquery = "SELECT photoid FROM data_photo ORDER BY photoid DESC LIMIT 1";
$newresult = mysql_query($newquery);
$row = mysql_fetch_object($newresult);
$newid = $row->photoid;
# copy the file to the images directory and make a thumbnail...
$upfile = "images/".$newid.".jpg";
# determine image dimensions for thumbnail creation...
$size = getimagesize($userfile);
$width = $size[0];
$height = $size[1];
$lesser_dim = $width;
if ($width > $height) $lesser_dim = $height; # work out if image is tall or wide.
$userfile_xstart = floor(($width-$lesser_dim)/2)+5; # add 5 to avoid a black border...
$userfile_ystart = floor(($height-$lesser_dim)/2)+5; # same here.
$thumb = imagecreate (120, 120); # a new image object for the thumbnail.
$source = imagecreatefromjpeg($userfile);
# resize $userimage and place in the thumbnail (-5's are to avoid black borders).
if (!imagecopyresized($thumb, $source, 0, 0, $userfile_xstart, $userfile_ystart, 120, 120, $lesser_dim-5, $lesser_dim-5)) {
return "Problem: Could not resize source image for thumbnail creation.";
exit;
}
# set the interlacing of the 2 images to 0 (so that they load gradually to the screen).
imageinterlace ($thumb, 0);
# save the thumbnail in the thumbnail dir...
if (!imagejpeg($thumb, "images/thumb/".$newid.".jpg", 80))
{
return "Problem: Could not save thumbnail in directory.";
exit;
}
# copy the source image to the images directory...
if (!copy($userfile, $upfile))
{
return "Problem: Could not move temp file into destination directory.";
exit;
}
return "The image "$title, $subject" was added to the database successfully.";
}
?>Cheers,
Gareth