Skip to content
Advertisement

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);
    }

Advertisement

Answer

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 is unnecessary in this case – you can remove it

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement