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

// 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


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


// this line actually does the image resizing, copying from the original image into the $tmp image

// 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'];

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

return $filename;

Smart Image Resizer
Smart Image Resizing while Preserving Transparency With PHP and GD Library

Related Posts: