How to reduce or compress image size while uploading using PHP | Mitrajit's Tech Blog

Image Compression Tool

  • Allowed image types are -- .jpg|.jpeg|.gif|.png.
0) { echo '

Increase post_max_size and upload_max_filesize limit in php.ini file.

'; } else { if($_FILES['uploadImg']['size'] / 1024 <= 5120) { // 5MB if($_FILES['uploadImg']['type'] == 'image/jpeg' || $_FILES['uploadImg']['type'] == 'image/pjpeg' || $_FILES['uploadImg']['type'] == 'image/png' || $_FILES['uploadImg']['type'] == 'image/gif'){ $source_file = $_FILES['uploadImg']['tmp_name']; $target_file = "uploads/compressed_" . $_FILES['uploadImg']['name']; $width = $_POST['width']; $height = $_POST['height']; $quality = $_POST['quality']; //$image_name = $_FILES['uploadImg']['name']; $success = compress_image($source_file, $target_file, $width, $height, $quality); if($success) { // Optional. The original file is uploaded to the server only for the comparison purpose. copy($source_file, "uploads/original_" . $_FILES['uploadImg']['name']); } } } else { echo '

Image should be maximun 5MB in size!

'; } } } else { echo "

Please select an image first!

"; } } ?>
" target="_blank" title="View actual size"> '>
Original : KB
" target="_blank" title="View actual size"> '>
Compressed : KB
0)) $nwidth = $image_info[0]; if(!($nheight > 0)) $nheight = $image_info[1]; if(!empty($image_info)) { switch($image_info['mime']) { case 'image/jpeg' : if($quality == '' || $quality < 0 || $quality > 100) $quality = 75; //Default quality // Create a new image from the file or the url. $image = imagecreatefromjpeg($source_file); $thumb = imagecreatetruecolor($nwidth, $nheight); //Resize the $thumb image imagecopyresized($thumb, $image, 0, 0, 0, 0, $nwidth, $nheight, $image_info[0], $image_info[1]); // Output image to the browser or file. return imagejpeg($thumb, $target_file, $quality); break; case 'image/png' : if($quality == '' || $quality < 0 || $quality > 9) $quality = 6; //Default quality // Create a new image from the file or the url. $image = imagecreatefrompng($source_file); $thumb = imagecreatetruecolor($nwidth, $nheight); //Resize the $thumb image imagecopyresized($thumb, $image, 0, 0, 0, 0, $nwidth, $nheight, $image_info[0], $image_info[1]); // Output image to the browser or file. return imagepng($thumb, $target_file, $quality); break; case 'image/gif' : if($quality == '' || $quality < 0 || $quality > 100) $quality = 75; //Default quality // Create a new image from the file or the url. $image = imagecreatefromgif($source_file); $thumb = imagecreatetruecolor($nwidth, $nheight); //Resize the $thumb image imagecopyresized($thumb, $image, 0, 0, 0, 0, $nwidth, $nheight, $image_info[0], $image_info[1]); // Output image to the browser or file. return imagegif($thumb, $target_file, $quality); //$success = true; break; default: echo "

Not supported file type!

"; break; } } } ?>