Pages

Sunday, January 15, 2012

PHP: Image Uploader

Here is an image uploader with re-sizing methods
<?php

/**
 * @file ImageUploader.php
 * @author Abhishek Kumar
**/

$tempFile = $_FILES['Filedata']['tmp_name'];
$fileName = $_FILES['Filedata']['name'];
$fileSize = $_FILES['Filedata']['size'];

$timestamp = date("YmdHis");
$new_fileName = "IMG".$timestamp.strtolower(getFileExtension($fileName));
move_uploaded_file($tempFile, "warehouse/" . $new_fileName);

echo $new_fileName;
 
function getFileExtension($iFile)
{
 $iExtension = strrpos($iFile, ".");
 $oExtension = substr($iFile, $iExtension, strlen($iFile));
 $oString = strtolower($oExtension);
 return $oString;
}

function imageResizer($image)
{
 //$image = "Database/Foto/IMG_001.jpg"; // Name of the source image
 list($PictureWidth, $PictureHeight) = getimagesize($image); // Get original size of source image
 
 $PictureAspectRatio = $PictureWidth/$PictureHeight;

 $Width = 160;
 $Height = 120;
 $AspectRatio = $Width/$Height;
 
 if ($PictureAspectRatio > $AspectRatio)
 {
  $NewWidth = $Width;
  $NewHeight = $Width/$PictureWidth * $PictureHeight;
 }
 else if ($PictureAspectRatio < $AspectRatio)
 {
  $NewWidth = $Height/$PictureHeight * $PictureWidth;
  $NewHeight = $Height;
 }
 else if ($PictureAspectRatio == $AspectRatio)
 {
  $NewWidth = $Width;
  $NewHeight = $Height;
 }
 
 # Generate the resources
 $thumb = imagecreatetruecolor($NewWidth, $NewHeight); // Create resource for thumbnail
 $source = imagecreatefromjpeg($image); // Set the resource for the source image
 
 # Generate the actual thumbnail
 imagecopyresized($thumb, $source, 0,0,0,0, $NewWidth, $NewHeight, $PictureWidth, $PictureHeight); // Generate thumbnail data
 
 # Stream the data to a filename
 imagejpeg($thumb,$image,50); // Stream image to file 'original_thumbnail.jpg'
 
 # Release the memory
 imagedestroy($thumb); // Always remember to clear your resources!
 imagedestroy($source); // Otherwise, you get a "memory leak" 
}

?>

No comments:

Post a Comment