Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Compress image with PHP not reducing image size

I’m trying to compress and upload an image to the server with PHP. The upload are working correctly (without any errors), however the image size remains the same after the upload has completed. Could someone please advise what I could possibly be doing wrong?

Please find the code below:

   public function addcoverimageAction()
    {

        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            // Sanitize POST array
            $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);

            $userid = $this->route_params['userid'];
            $thisuser = $userid;
            $postid = $this->route_params['postid'];

            $path_parts = pathinfo($_FILES['file']['name']);
            $filename = $path_parts['filename'] . '_' . microtime(true) . '.' . $path_parts['extension'];

            $directoryName = dirname(__DIR__) . "/images/$thisuser/listings/$postid/coverimage/";
          
            // Check if directory exist

            if (!is_dir($directoryName)) {

             //If directory does net exist - create directory
                mkdir($directoryName, 0777, true);
            }

            // Compress image
            function compressImage($source, $destination, $quality)
            {

                $info = getimagesize($source);

                if ($info['mime'] == 'image/jpeg') $image = imagecreatefromjpeg($source);

                elseif ($info['mime'] == 'image/png') $image = imagecreatefrompng($source);

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

             compressImage($_FILES['file']['tmp_name'], $directoryName . $filename, 60);

            // Upload image
            move_uploaded_file($_FILES['file']['tmp_name'], $directoryName . $filename);
        }

        $this->post = Post::findByID($postid);
        Post::updateCoverimage($filename, $postid);
    }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If it is working, then you’re immediately overwriting the compressed file with the original, via the move_uploaded_file command, because you’re sending it to the same destination as the compressed file, which was an earlier step.

The move_uploaded_file command should be unnecessary in this case – try removing it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading