How To Compress images With PHP






Step1-Create an index.php file




<form action="upload.php" method="post" enctype="multipart/form-data">
    <label>Select Image File:</label>
    <input type="file" name="image">
    <input type="submit" name="submit" value="Upload">

</form>

Step2-create a upload.php file and also a images folder




<?php  
function ReduceImagesize($source$destination$quality
{
    $imgInfo getimagesize($source);
    $mime $imgInfo['mime'];
    
    switch($mime){
        case 'image/bmp':
            $image imagecreatefrombmp($source);
            break;    

     case 'image/tiff':
            $image imagecreatefromtiff($source);
            break;


        case 'image/jpeg':
            $image imagecreatefromjpeg($source);
            break;
        case 'image/png':
            $image imagecreatefrompng($source);
            break;
        case 'image/gif':
            $image imagecreatefromgif($source);
            break;
        default:
            $image imagecreatefromjpeg($source);
    }
    
    imagejpeg($image$destination$quality);
    
    return $destination;
}

 $uploadPath "images/";
$status $statusMsg5 '';
if(isset($_POST["submit"])){
    $status 'error in uploading';
    if(!empty($_FILES["image"]["name"])) {
        $fileName basename($_FILES["image"]["name"]);
        $imageUploadPath $uploadPath $fileName;
        $fileType pathinfo($imageUploadPathPATHINFO_EXTENSION);
        
        $allowTypes = array('bmp', 'tiff','jpg','png','jpeg','gif');
        if(in_array($fileType$allowTypes)){
            $imageTemp $_FILES["image"]["tmp_name"];
            
           
            $compressedpic ReduceImagesize ($imageTemp$imageUploadPath75);
            
            if($compressedpic){
                $status 'success';
                $statusMsg5 " compressed successfully.";
            }else{
                $statusMsg5 " compression  failed!";
            }
        }else{
            $statusMsg5 'Sorry, only BMP,TIFF, JPG, JPEG, PNG, & GIF files are allowed  .';
        }
    }else{
        $statusMsg5 'Please select an images file to upload.';
    }
}
 echo $statusMsg5;
 ?>


Previous
Next Post »
Thanks for your comment