user8143979
user8143979

Reputation: 127

How to compress image size before uploading using php

I already searched lots of stuff, some of them are from stackoverflow. But none of them helped me. What I want to do is reduce the image file size, and after reducing the image will now be uploaded. Here's my current code:

<?php

include 'cloud_functions.php';


// GET THE USER'S ID
$userid = _clean($con, $_POST['userid']);


if(!is_dir("uploads/user/".$userid."/")){
        mkdir("uploads/user/".$userid."/", 0755);
}


$temp = explode(".", _clean($con,$_FILES["file"]["name"]));


$targetPath = "uploads/user/".$userid."/";
// RENAME THE IMAGE USING ROUND();
$newFN = round(microtime(true)) . '.' . end($temp);
$targetPath = $targetPath .  $newFN;
// GET THE FILE EXTENSION
$type = pathinfo(_clean($con, $_POST['filename']), PATHINFO_EXTENSION);

$all_types = array('jpg', 'png', 'jpeg');
$type = strtolower($type);

if(in_array($type, $all_types)){

    if(move_uploaded_file($_FILES['file']['tmp_name'], $targetPath)){
        // image uploaded w/o compressing size
        echo "1/".$newFN;
    }else{
        echo $targetPath;
        echo "There was an error uploading the file, please try again!";
    }

}else{
    echo "Please upload a valid image.";
}


?>

In that way I can upload image successfully without compressing its size. Please tell me how to do compress image size before upload. Thanks.

Upvotes: 0

Views: 5794

Answers (2)

M Hussain
M Hussain

Reputation: 381

You need to compress image on client side. All the code you posted here is of server side. This code will run after uploading the image to the server. There are lot of client side libraries for this purpose. This link will further help. You can choose use any library of your choice.

Upvotes: 1

tre
tre

Reputation: 915

https://github.com/brunobar79/J-I-C - js library

I think better way - compress image on server after uploading, that to decrease using user memory. It's special important for slow smartphones.

Upvotes: 0

Related Questions