Compress image on upload php

7.3k views Asked by At

I am trying to add a function to reduce filesize when an image is uploaded, I have the code to upload the image and it works fine but am new to this all together.. Would I use imagejpeg for this or is there a better (more simple) way? I have not included my attempts as they have failed so here is the working standard upload script using a basic submit file input..

$file_formats = array("jpg","jpeg","JPEG",'PNG', "png", "gif", "bmp");

$filepath = "upload_images/";


if ($_POST['submitbtn']=="Submit") {
 $name = $_FILES['imagefile']['name'];
 $size = $_FILES['imagefile']['size'];
if (strlen($name)) {
$extension = substr($name, strrpos($name, '.')+1);
if (in_array($extension, $file_formats)) { 
    if ($size < (2048 * 1024)) { 
        $imagename = md5(uniqid() . time()) . "." . $extension;
        $tmp = $_FILES['imagefile']['tmp_name'];


            if (move_uploaded_file($tmp, $filepath . $imagename)) {

                //execute function once uploaded

            } else {
                echo "Could not move the file.";
            }
    } else {
        echo "Your image size is bigger than 2MB.";
    }
} else {
        echo "Invalid file format.";
}
} else {
        echo "Please select image..!";
}

}
1

There are 1 answers

0
Ryan D On

ok so I found my solution and its as simple as it gets..

http://www.nimrodstech.com/php-image-resize/

I use my existing upload code posted above and used this plugin to reduce the size after its uploaded.. +1 mate!