unknown os platform
resize image proportionally on upload and save in PHP | Whats-online.info
whats-online-info

resize image proportionally on upload and save in PHP


resize
2016/10/01 / Science and Tutorials

Learn how to create a php function that will resize image on upload proportionally and save the resized photo in a new directory.






You can download this code example at the end of this tutorial



In this tutorial, I will teach how to resize an image proportionally on upload, that is, 'keep aspect ratio.' Also, restrict the new image height and width to a certain maximum size in PHP. 

Advantages of resizing images on or before upload
-Image size is reduced, and the bandwidth consumed in uploading the image is also reduced.
-It facilitates faster uploading of the image to the server

Advantages of resizing images after upload
-Reduces the storage space
-Reduces the image file rendering time and caching on a browser.
-Reduces the web page size
-Reduces the page rendering time thus increases the page speed. (This one factor enhances SEO on your website).

First and foremost, we need to create an HTML form to layout our file chooser and the upload button. Set form action to the current file name, the method to post, enctype to multipart/ form-data as shown.

Our HTML code
<form action="<?php echo $_SERVER["SCRIPT_NAME"];?>" enctype="multipart/form-data" method="post"> <label>Select Image </label><br/><br/> <input type="file" name="upload"/><br/> <br/><input type="submit" value="upload"/> </form>

Then we need to post and resize our image file based on the specified maximum width and maximum height to the server using PHP script.
We will create two PHP files
First PHP file to handle the image posting and uploading to the server as shown below.

The first php file
Post the image and submit the resized image to the server. Calls the function for image file resizing

The second PHP file will handle the image resizing as shown below. I will take through this code snippet bits by bits.
First, we will create a function called makeThumbnail() which holds five arguments as shown.

makeThumbnail($sourcefile,$max_width, $max_height, $endfile, $type){}

Argument 1 ($sourcefile) gets the directory of the original file in the temporary location
Argument 2 ($max_width)  Determines the maximum width to resize image
Argument 3 ($max_height)  Determines the maximum height to resize image
Argument 4 ($endfile)   Specifies the directory in which the resized image should be saved
Argument 5 ($type) Determines the file extension and restricts the resizing action to only Png, Gif, and JPEG files format

We will use the switch statement to check the type of our file extension as shown below.

switch($type){ case'image/png': $img = imagecreatefrompng($sourcefile); break; case'image/jpeg': $img = imagecreatefromjpeg($sourcefile); break; case'image/gif': $img = imagecreatefromgif($sourcefile); break; default :  return 'Un supported format'; }

Next, this is the part of the code which requires the maximum attention. Determining our divisor.  First, we need to get the width and height of our original image as shown below. 

$width = imagesx( $img ); $height = imagesy( $img );

We need to check which dimension of the image is greater than and then we use it to get the divisor as shown below.

How to get our divisor mathematically
lets assume our original image has width x and height y;
x=300 and y = 700

Maximum height and maximum width  is 200;

first, we will check which dimension of the image is greater than the other.
Our height (y) is greater than width(x) 

secondly, we check if our height is greater than our maximum height.
For our case, our height is greater than the maximum height. In a case where it less that the maximum height, we set our new height to our original height.

Finally, we look for our divisor as shown below

if y is set to maximum height 200
y=200, that is 
if 700=200
what about 
300=?
new width = (200 (new height) * 300(width)) / 700 (height)
so our divisor is
divisor= new height (300) / height(700) 
new width = divisor * width or width / (1/divisor)

and vice versa for the width if it greater than height

Divisor code

if ($width > $height) {     if($width < $max_width) $newwidth = $width; else     $newwidth = $max_width;     $divisor = $width / $newwidth;     $newheight = floor( $height / $divisor); } else { if($height < $max_height)          $newheight = $height;      else $newheight =  $max_height;       $divisor = $height / $newheight;     $newwidth = floor( $width / $divisor ); }

Then in order to maintain the quality of the image, we will use imageCopyResampled() function to resize the image as shown below 

imagecopyresampled( $tmpimg, $img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

Finally, release the memory. imagedestroy() function is used to clear the memory BEFORE the script ends. This is useful to keep memory usage during the script to an acceptable level.

  imagedestroy($tmpimg);    imagedestroy($img);

Full code

index.php
 contains form and prints out the resized image

<!DOCTYPE HTML> <html> <head>     <meta charset="utf-8"/> <title>PHP Image Resize</title> <style> body,header,section,footer{ display:block; width:100%; } body{ height:auto; } header{             height:auto; background:#ffffff;             position:fixed; min-width:1000px; z-index:5; } #header{ min-width:1000px; width:90%; margin:auto; text-align:center; padding:5px 0px; } section{ height:700px; position:absolute; top:100px; background:url(images/bg.png); background-repeat:no-repeat; background-position: right; z-index:1;   min-width:1000px; } footer{ width:100%; height:150px; background:#005070; position:absolute; top:1300px; z-index:10; margin-top:50px; } </style>      <meta name="viewport" content="width=device-width, initial-scale=1.0" />   </head> <body> <header>    <div id="header"> <h1>PHP Image Resize "Maintain Aspect Ratio"</h1> </div>  </header> <section> <div style="width:500px;margin:auto;"> <?php require"Post.php"; ?> </div></br> <form style="width:500px;margin:auto;" action="<?php echo $_SERVER["SCRIPT_NAME"];?>" enctype="multipart/form-data" method="post"> <label>Select Image </label><br/><br/> <input type="file" name="upload" style="width:300px;padding:5px;border:1px solid #e0e0e0;"/><br/> <br/><input type="submit" value="upload"/> </form> </br><div style="width:500px;margin:auto;"> <?php echo "Resized image<br/><br/><img src=".$endfile.""; ?> </div> </section> </body> </html>

Post.php

post the image and submit it to the server. Calls the function for image file resizing

<?php require"resize-image.php"; $endfile=""; if(isset($_FILES['upload']['name'])){ $sourcefile= $_FILES['upload']['tmp_name']; $endfile= $_FILES['upload']['name']; $type=$_FILES['upload']['type']; makeThumbnail($sourcefile, $max_width=100, $max_height=100, $endfile, $type); //Insert into database the file name //$query="insert into table values('$endfile')"; } ?>

resize-image.php

<?php function makeThumbnail($sourcefile,$max_width, $max_height, $endfile, $type){ // Takes the sourcefile (path/to/image.jpg) and makes a thumbnail from it // and places it at endfile (path/to/thumb.jpg). // Load image and get image size.     //    switch($type){ case'image/png': $img = imagecreatefrompng($sourcefile); break; case'image/jpeg': $img = imagecreatefromjpeg($sourcefile); break; case'image/gif': $img = imagecreatefromgif($sourcefile); break; default :  return 'Un supported format'; } $width = imagesx( $img ); $height = imagesy( $img ); if ($width > $height) {     if($width < $max_width) $newwidth = $width; else     $newwidth = $max_width;     $divisor = $width / $newwidth;     $newheight = floor( $height / $divisor); } else { if($height < $max_height)          $newheight = $height;      else $newheight =  $max_height;       $divisor = $height / $newheight;     $newwidth = floor( $width / $divisor ); } // Create a new temporary image. $tmpimg = imagecreatetruecolor( $newwidth, $newheight );     imagealphablending($tmpimg, false);     imagesavealpha($tmpimg, true); // Copy and resize old image into new image. imagecopyresampled( $tmpimg, $img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); // Save thumbnail into a file. //compressing the file switch($type){ case'image/png': imagepng($tmpimg, $endfile, 0); break; case'image/jpeg': imagejpeg($tmpimg, $endfile, 100); break; case'image/gif': imagegif($tmpimg, $endfile, 0); break; } // release the memory    imagedestroy($tmpimg);    imagedestroy($img); } ?>

Congrats, we are done. We have managed to resize our image before upload and submit it to the server and retrieve and display the new image with the new width and height. Note, we have not compressed the image at all. 













You may also like:


Leave a comment












Subscribe to get replies direct to your mailbox

Submit comment