Image Upload and Proportional Resize with php


PHP has the ability to upload files(images/docs) using the multipart/form-data protocol.

To upload files, in a form you have to specify enctype="multipart/form-data", so that you can upload files.

// This is the temporary file created by PHP
$uploadedfile = $_FILES['image']['tmp_name'];

// Create an Image from it so we can do the resize
$image = $_FILES['image'];
$ext = strtolower(substr(strrchr($image['name'], "."), 1));

if($ext=='jpg' || $ext=='jpeg')
{
$src = imagecreatefromjpeg($uploadedfile);
}
else if($ext=='gif')
{
$src = imagecreatefromgif($uploadedfile);
}
else if($ext=='png')
{
$src = imagecreatefrompng($uploadedfile);
}
// This capture the original size of the uploaded image
list($width,$height)=getimagesize($uploadedfile);

// For our purposes, I have resized the image to be 100 pixels wide, and maintain the original aspect ratio. This prevents the image from being "stretched" or "squashed". If you prefer some max width other than 100, simply change the $target variable

$target=100;

if ($width > $height) {
$percentage = ($target / $width);
}else {
$percentage = ($target / $height);
}
$newwidth = round($width * $percentage);
$newheight = round($height * $percentage);

$tmp=imagecreatetruecolor($newwidth,$newheight);

// this line actually does the image resizing, copying from the original image into the $tmp image
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

// now write the resized image to disk. I have assumed that you want the resized, uploaded image file to reside in the ./images subdirectory.
$filename = "images/". $_FILES['image']['name'];
imagejpeg($tmp,$filename,100);

imagedestroy($src);
imagedestroy($tmp); // NOTE: PHP will clean up the temp file it created when the request has completed.

return $filename;

References:
class.upload.php
Smart Image Resizer
Smart Image Resizing while Preserving Transparency With PHP and GD Library

Related Posts: