Resize Image While Uploading with PHP

On my previous post I was shown an example how to upload file with php and html. It was based on php simple image upload functionality. Today I am going to show you little bit advance of image uploading. Suppose if you run a website and want to allow users to upload image files than you need to think little bit about server's space and bandwidth. For this purpose you need to do some optimization with image files. Image resize while uploading is one of them. All major website do it in the same way. If a user uploads a 5mb image file they resize it in different sizes and store on there server. It helps them to seed up there website and reduce there budget. Now take a look, how we can do it ourself.

Live Demo Download Source
PHP and HTML(index.php)
This file holds the basic of file uploading html markup and simple php upload handler.
<?php
include( 'function.php');
// settings
$max_file_size = 1024*200; // 200kb
$valid_exts = array('jpeg', 'jpg', 'png', 'gif');
// thumbnail sizes
$sizes = array(100 => 100, 150 => 150, 250 => 250);

if ($_SERVER['REQUEST_METHOD'] == 'POST' AND isset($_FILES['image'])) {
  if( $_FILES['image']['size'] < $max_file_size ){
    // get file extension
    $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
    if (in_array($ext, $valid_exts)) {
      /* resize image */
      foreach ($sizes as $w => $h) {
        $files[] = resize($w, $h);
      }

    } else {
      $msg = 'Unsupported file';
    }
  } else{
    $msg = 'Please upload image smaller than 200KB';
  }
}
?>
<html>
<head>
  <title>Image resize while uploadin</title>
<head>
<body>
  <!-- file uploading form -->
  <form action="" method="post" enctype="multipart/form-data">
    <label>
      <span>Choose image</span>
      <input type="file" name="image" accept="image/*" />
    </label>
    <input type="submit" value="Upload" />
  </form>
</body>
</html>

Resize Function(function.php):
Resize function is based on PHP GD library.
/**
 * Image resize
 * @param int $width
 * @param int $height
 */
function resize($width, $height){
  /* Get original image x y*/
  list($w, $h) = getimagesize($_FILES['image']['tmp_name']);
  /* calculate new image size with ratio */
  $ratio = max($width/$w, $height/$h);
  $h = ceil($height / $ratio);
  $x = ($w - $width / $ratio) / 2;
  $w = ceil($width / $ratio);
  /* new file name */
  $path = 'uploads/'.$width.'x'.$height.'_'.$_FILES['image']['name'];
  /* read binary data from image file */
  $imgString = file_get_contents($_FILES['image']['tmp_name']);
  /* create image from string */
  $image = imagecreatefromstring($imgString);
  $tmp = imagecreatetruecolor($width, $height);
  imagecopyresampled($tmp, $image,
    0, 0,
    $x, 0,
    $width, $height,
    $w, $h);
  /* Save image */
  switch ($_FILES['image']['type']) {
    case 'image/jpeg':
      imagejpeg($tmp, $path, 100);
      break;
    case 'image/png':
      imagepng($tmp, $path, 0);
      break;
    case 'image/gif':
      imagegif($tmp, $path);
      break;
    default:
      exit;
      break;
  }
  return $path;
  /* cleanup memory */
  imagedestroy($image);
  imagedestroy($tmp);
}

32 comments:

  1. Hi make sure image uploading is blocked when the file input is empty

    ReplyDelete
    Replies
    1. Yeah! We can do it by applying isset($_FILES['image'] or is_uploaded_file($_FILES['image']['tmp_name'] condition

      Delete
    2. if(!empty($_FILES)) can even be used to block empty image field...

      Delete
  2. Its working..
    Thanks!

    ReplyDelete
  3. Is it possible to resize multiple images at same time using this way?

    ReplyDelete
    Replies
    1. Good question! Of course it is possible!
      You need to add multiple attributable on file input.
      For detail see here

      Delete
  4. how to resize images in shape of ladder ...

    ReplyDelete
  5. Hey I used class for this. How to resize multiple image using the same code. What part of the PHP code we need to change. Because when i tried to take images in loop, i got error of class can not be re-declared. Please help me off in this. Thanks in advance

    ReplyDelete
  6. There is a problem with resize when uploading .PNG image, it shows black image.

    ReplyDelete
    Replies
    1. Its all about transparency!

      Please see this resource: http://stackoverflow.com/questions/32243/can-png-image-transparency-be-preserved-when-using-phps-gdlib-imagecopyresample

      Delete
  7. Hi, can you tell me how to insert the name of the resized file into a DB? I am trying to insert it but am unsure which variable to use.

    Thanks!

    ReplyDelete
    Replies
    1. You can store original file name using $_FILES['image']['name'] and rather you can call your file like this way uploads/100x100_yourfilename.jpg

      Delete
  8. Is there a quick modification that would allow this to respect the aspect ratio of the original file? Currently all images are cropped according to the height and width parameters? Is there a way to set the width to auto?

    ReplyDelete
  9. Would like to keep the aspect ratio too, as NativePaul mentioned! Examples?

    ReplyDelete
  10. I'm not a PHP expert but once you retun a value form a function what's after is not executed.
    So this code is never reached:
    /* cleanup memory */
    imagedestroy($image);
    imagedestroy($tmp);

    ReplyDelete
    Replies
    1. That is correct. Once a return is reached, the function is exited. The return should ALWAYS (ok, there are few exceptions...) be the last line of a function

      Delete
  11. doesn't work in IE8... :(

    ReplyDelete
  12. Thanks, Well done

    ReplyDelete
  13. the code is cropping the image..i should get original image instead of cropping...help me please...

    ReplyDelete
  14. sir, can i send these three resisizes Pics in differnt folder insted sending only one folder "UPLOADS"
    pls reply i really needed this thing

    ReplyDelete
  15. Thx for the code, only one thing tho, whatever it is affter the return won't be executed, so your function isn't cleaning up the memory. Just move the return at the bottom ;)

    ReplyDelete
  16. Great code, can you please tell me how I can change this code, so I can uploade multiple images? And not one by one?
    Kind regards
    Nancy De Lange
    info@pixelduo.be

    ReplyDelete
  17. while uplodaing image as png it takes black color as in border?what to do now?

    ReplyDelete
  18. Please reply to the aspect ratio questions. I'm looking for the answer also.

    ReplyDelete
  19. How can upload this resized image into mysql?please give the code

    ReplyDelete
  20. Warning: imagejpeg(uploads/100x100_d90e6063f6246b6033581135e9f81a4c510fa220.jpg): failed to open stream: No such file or directory in /home/w3bees/public_html/demo/resize-image-while-uploading/function.php on line 36 <------this error came out when i ply it on the demo, what actually happen ??

    ReplyDelete
  21. Warning: imagejpeg(uploads/100x100_Android.jpg): failed to open stream: No such file or directory in /home/w3bees/public_html/demo/resize-image-while-uploading/function.php on line 36

    Warning: imagejpeg(uploads/150x150_Android.jpg): failed to open stream: No such file or directory in /home/w3bees/public_html/demo/resize-image-while-uploading/function.php on line 36

    Warning: imagejpeg(uploads/250x250_Android.jpg): failed to open stream: No such file or directory in /home/w3bees/public_html/demo/resize-image-while-uploading/function.php on line 36
    Image resize while uploading

    ReplyDelete
  22. Fatal error: Call to undefined function resize() in C:
    what should i do :( please help me out

    ReplyDelete

Go to top