When we work on some website where the user or administrator of the website can upload new images by some
CMS (Content Management System), we can think on this, how the pictures will be organized. Probably
uploaded pictures by the users or administrators will don't pass any standards on our website for dimensions, size, orientation, etc. Also if you want to have one
thumbnail image for each picture you have to require from the users or administrators to upload one more small version of the picture.
For this we have to
resize the pictures automatically immediately after their uploading or
resize in real time when displaying.
With this tutorial I will show you
How to Resize in real time (or the fly) or How Create Thumbnail of pictures with PHP GD library.
Here is the complete HTML form with file input, browse button and submit button. This have to be saved in an HTML file on the web server.
Please note that the form have one more addition parameter - enctype="multipart/form-data". This parameter need when the form have to send binary data like file uploads.
Now we will extend a little bit upload.php file and here is complete
PHP code for the image upload, resize using GD library and saving the resized thumbnail.
Please note that the example in our tutorial read JPG files. And for this reason we included check on the file name extension for this. If you need support for creating thumbnails from/for different file format check PHP GD library documentation.
<?php
// set folder for saving uploaded images
$save_to="/httpdocs/images";
// set folder for saving thumbnails of uploaded images
$thumb_save_to="/httpdocs/images/thumbs";
// default width of thumbnails (in pixels)
$thumb_w=100;
if ($_POST['send_upload']==1) {
if (is_uploaded_file($_FILES['file_upload']['tmp_name'])) {
$file_name=$_FILES['file_upload']['name'];
move_uploaded_file($_FILES['file_upload']['tmp_name'], $save_to."/".basename($file_name));
echo $file_name." was uplaoded successfully";
// get file extension
$ex=strtolower(substr($file['name'], strrpos($file['name'], ".")+1, strlen($file['name'])));
if ($ex=="jpg") {
// read the uploaded JPG file
$img=imagecreatefromjpeg($save_to."/".basename($file_name));
// get dimension of the image
$ow=imagesx($img);
$oh=imagesy($img);
// keep aspect ratio
$scale=$thumb_w/$ow;
$h=round($oh*$scale);
$newimg=imagecreatetruecolor($thumb_w,$h);
imagecopyresampled($newimg,$img,0,0,0,0,$thumb_w,$h,$ow,$oh);
// saving the JPG thumbnail
imagejpeg($newimg, $thumb_save_to."/".$file_name, 90);
} else {
echo "No thumbnail was generated - only JPG files are supported.";
}
} else {
echo "Error was occured while uploading!";
}
}
?>