Search code examples
phpimage-compression

Unable to reduce image file size in php while uploading


I following code can upload multiple image and rename them while upload and it works fine.Then i tried to implement image compress but this doesn't work, can someone help me to solve this issue.

Without compress method

if (!empty($_POST)) {
    $newname = md5(rand() * time());
    if (isset($_FILES['files'])) {
        $uploadedFiles = array();
        foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name) {
            $errors = array();
            $file_name = md5(uniqid("") . time());
            $file_size = $_FILES['files']['size'][$key];
            $file_tmp = $_FILES['files']['tmp_name'][$key];
            $file_type = $_FILES['files']['type'][$key];
            if ($file_type == "image/gif") {
                $sExt = ".gif";
            } elseif ($file_type == "image/jpeg" || $file_type == "image/pjpeg") {
                $sExt = ".jpg";
            } elseif ($file_type == "image/png" || $file_type == "image/x-png") {
                $sExt = ".png";
            }
            if (!in_array($sExt, array('.gif', '.jpg', '.png'))) {
                $errors[] = "Image types alowed are (.gif, .jpg, .png) only!";
            }
            if ($file_size > 2097152000) {
                $errors[] = 'File size must be less than 2 MB';
            }
            $desired_dir = "upload/";
            if (empty($errors)) {
                if (is_dir($desired_dir) == false) {
                    mkdir("$desired_dir", 0700);
                }
                if (move_uploaded_file($file_tmp, "$desired_dir/" . $file_name . $sExt)) {
                    $uploadedFiles[$key] = array($file_name . $sExt, 1);
                } else {
                    echo "Couldn't upload file " . $_FILES['files']['name'][$key];
                    $uploadedFiles[$key] = array($_FILES['files']['name'][$key], 0);
                }
            } else {

            }
        }
        foreach ($uploadedFiles as $key => $row) {
            if (!empty($row[1])) {
                $codestr = '$file' . ($key + 1) . ' = $row[0];';
                eval($codestr);
            } else {
                $codestr = '$file' . ($key + 1) . ' = NULL;';
                eval($codestr);
            }
        }
    }

With compress method

if (!empty($_POST)) {
    $newname = md5(rand() * time());
    if (isset($_FILES['files'])) {
        $uploadedFiles = array();
        foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name) {
            $errors = array();
            $file_name = md5(uniqid("") . time());
            $file_size = $_FILES['files']['size'][$key];
            $file_tmp = $_FILES['files']['tmp_name'][$key];
            $file_type = $_FILES['files']['type'][$key];
            if ($file_type == "image/gif") {
                $sExt = ".gif";
            } elseif ($file_type == "image/jpeg" || $file_type == "image/pjpeg") {
                $sExt = ".jpg";
            } elseif ($file_type == "image/png" || $file_type == "image/x-png") {
                $sExt = ".png";
            }
            if (!in_array($sExt, array('.gif', '.jpg', '.png'))) {
                $errors[] = "Image types alowed are (.gif, .jpg, .png) only!";
            }
            if ($file_size > 2097152000) {
                $errors[] = 'File size must be less than 2 MB';
            }
            $desired_dir = "upload/";
            if (empty($errors)) {
                if (is_dir($desired_dir) == false) {
                    mkdir("$desired_dir", 0700);
                }
                if (move_uploaded_file($file_tmp, "$desired_dir/" . $file_name . $sExt)) {
                    $uploadedFiles[$key] = array($file_name . $sExt, 1);
                } else {
                    echo "Couldn't upload file " . $_FILES['files']['name'][$key];
                    $uploadedFiles[$key] = array($_FILES['files']['name'][$key], 0);
                }
            } else {

            }
        }

function compress($source, $destination, $quality) {

    $info = getimagesize($source);

    if ($info['mime'] == 'image/jpeg') {
                $image = imagecreatefromjpeg($source);
            } elseif ($info['mime'] == 'image/gif') {
                $image = imagecreatefromgif($source);
            } elseif ($info['mime'] == 'image/png') {
                $image = imagecreatefrompng($source);
            }

            imagejpeg($image, $destination, $quality);

    return $destination;
}
$source_img = $uploadedFiles;
$destination_img = 'compres/';

$d = compress($source_img, $destination_img, 60);

        foreach ($uploadedFiles as $key => $row) {
            if (!empty($row[1])) {
                $codestr = '$file' . ($key + 1) . ' = $row[0];';
                eval($codestr);
            } else {
                $codestr = '$file' . ($key + 1) . ' = NULL;';
                eval($codestr);
            }
        }
    }

Solution

  • The problem with your code is that $file_name is the same for all images. Also you did not get the correct image resource. Here is the working solution:

    <?php 
    if (!empty($_POST)) {
        $newname = md5(rand() * time());
        if (isset($_FILES['files'])) {
            $uploadedFiles = array();
            foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name) {
                $errors = array();
                $file_name = md5(uniqid("") . time());
                sleep(1);//We give a second for breathing
                $file_size = $_FILES['files']['size'][$key];
                $file_tmp = $_FILES['files']['tmp_name'][$key];
                $file_type = $_FILES['files']['type'][$key];
                $filename = $_FILES["files"]["name"][$key];
    
                if ($file_type == "image/gif") {
                    $sExt = ".gif";
                } elseif ($file_type == "image/jpeg" || $file_type == "image/pjpeg") {
                    $sExt = ".jpg";
                } elseif ($file_type == "image/png" || $file_type == "image/x-png") {
                    $sExt = ".png";
                }
                if (!in_array($sExt, array('.gif', '.jpg', '.png'))) {
                    $errors[] = "Image types alowed are (.gif, .jpg, .png) only!";
                }
                if ($file_size > 2097152000) {
                    $errors[] = 'File size must be less than 2 MB';
                }
                $desired_dir = "upload/";
                if (empty($errors)) {
                    if (is_dir($desired_dir) == false) {
                        mkdir("$desired_dir", 0700);
                    }
                    if (move_uploaded_file($file_tmp, $desired_dir . $file_name . $sExt)) {
                        $uploadedFiles[$key] = array($file_name . $sExt, 1);
                    } else {
                        echo "Couldn't upload file " . $_FILES['files']['name'][$key];
                        $uploadedFiles[$key] = array($_FILES['files']['name'][$key], 0);
                    }
                } else {
                    print_r($errors);
                }
            }        
    
    function compress($filename, $destination, $quality) {        
                $info = getimagesize($filename);
                if ($info['mime'] == 'image/jpeg') {
                    $image = imagecreatefromjpeg($filename);
                } elseif ($info['mime'] == 'image/gif') {
                    $image = imagecreatefromgif($filename);
                } elseif($info['mime'] == 'image/png') {
                    $image = imagecreatefrompng($filename);
                }else{
                    $image =null;
                }                    
            return imagejpeg($image, $destination, $quality);
    }
    $compressed = 0;
    $destination_img = 'compressed/';
    foreach($uploadedFiles as $km=>$val){ 
       $photos = $desired_dir . $val[0];   
       $compressed += compress($photos, $destination_img.$val[0], 60);   
    }
        if($compressed>=1){
            echo $compressed.' Images compresses';
        }else{
            echo 'No Image Compressed';
        }       
        }
    }
        ?>
    <form method="POST" enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>">
        <input type="file" name="files[]">File 1<br>
        <input type="file" name="files[]">File 2<br>
        <input type="file" name="files[]">File 3<br>
        <input type="submit" name="filesubmit" value="Submit">
    </form>
    

    Check the following links to better understand how image processing and generation:

    1. imagejpeg()
    2. getimagesize()

    I hope my answer helps you.