<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="image" id="imageUpload" size="40"/><br />
<input type="submit" value="Upload" id="uploadButton" />
</form>
<?php
// =======================================================
// THE MAIN SCRIPT - UPLOADS AND CREATES A THUMBNAIL
// ========================================================
// Path To Images Directory
$idir = "images/";
// Path To Thumbnails Directory
$tdir = "images/thumbnails/";
// Maximum Width For Thumbnail Images
$twidth = "170";
// Maximum Height For Thumbnail Images
$theight = "140";
// Check to see if proper file format (currently, jpg, jpeg, pjpeg, png, gif)
if (
$_FILES['image']['type'] == "image/jpg" ||
$_FILES['image']['type'] == "image/jpeg" ||
$_FILES['image']['type'] == "image/pjpeg" ||
$_FILES['image']['type'] == "image/png" ||
$_FILES['image']['type'] == "image/gif")
{
// Check to see if image is over 5mb
if ($_FILES['image']['size'] > 5242880) {
echo "Your Image Is Over the 5MB limit.";
exit();
}
$fileEXT = $_FILES['image']['type'];
// Get the file extention, eg .jpg
$file_ext = strrchr($_FILES['image']['name'], '.');
// Get the current unix time, this will be used in the file name, better to use this method than rand(), less CPU and there is a chance that the rand function may return the same var
$time = time();
// Converge it all together, to place into the dir, file name and extention
$url = $idir . $time . $file_ext;
// Move the image to its perm location
$copy = copy($_FILES['image']['tmp_name'], $url);
// If the move was successful
if ($copy) {
switch ($fileEXT)
{
case 'image/jpeg':
$simg = imagecreatefromjpeg($url);
break;
case 'image/gif':
$simg = imagecreatefromgif($url);
break;
case 'image/png':
$simg = imagecreatefrompng($url);
break;
default:
return false;
}
// Make New Image For Thumbnail
$dimg = imagecreate($newwidth, $newheight);
// Create New Color Pallete
imagetruecolortopalette($simg, false, 256);
$palsize = ImageColorsTotal($simg);
// Counting Colors In The Image
for ($i = 0; $i < $palsize; $i++) {
$colors = ImageColorsForIndex($simg, $i);
// Tell The Server What Colors This Image Will Use
ImageColorAllocate($dimg, $colors['red'], $colors['green'], $colors['blue']);
}
// Copy Resized Image To The New Image
imagecopyresized($dimg, $simg, 0, 0, 0, 0, $newwidth, $newheight, $currwidth, $currheight);
// This is the end Thumbnail location
$thuURL = $tdir . $time . $file_ext;
switch ($fileEXT)
{
case 'image/jpeg':
$src = imagejpeg($dimg, $thuURL);
break;
case 'image/gif':
$src = imagegif($dimg, $thuURL);
break;
case 'image/png':
$src = imagepng($dimg, $thuURL);
break;
default:
$src = imagejpeg($dimg, $thuURL);
}
imagedestroy($simg); // Destroying The Temporary Image
imagedestroy($dimg); // Destroying The Other Temporary Image
echo "Upload went well";
} else {
$uploadError = "There was an error uploading your image";
exit();
}