0

I have a bit of my website where users can upload images on to the server. However, the images are around 5MB and that will add up fast. How can I compress these images on upload so they're at least a little bit smaller, without losing much quality at all?

Here's my upload code:

if (isset($_FILES['image'])) {

        $file_size = $_FILES['image']['size'];
        $file_tmp = $_FILES['image']['tmp_name'];
        $file_type = $_FILES['image']['type'];
        $file_ext = strtolower(end(explode('.', $_FILES['image']['name'])));
        $file_name = str_replace(" ", "-", strtolower($_POST['title'])) . "." . $file_ext;

        $extensions = array("jpeg", "jpg", "png");

        if (!in_array($file_ext, $extensions)) {
            $errors[] = "Extension not allowed, please choose a JPEG or PNG file.";
        }

        if (empty($errors)) {
            // $uploaded = move_uploaded_file($file_tmp, "../../uploads/" . $file_name);
            $uploaded = compress_image($file_tmp, "../../uploads/" . $file_name, 80);
        }
    } 
user2397282
  • 3,798
  • 15
  • 48
  • 94
  • I tried using the compress_image function as you can see at the bottom (commented out the move_uploaded_file function) but it doesn't seem to work – user2397282 Aug 02 '16 at 18:13
  • There is not only compress_image function if you go through the link given by @Fred you will also get to know about ImageMagick which is a native php extension to create and modify images using the ImageMagick API. Go through this link properly you will have your answers http://php.net/manual/en/book.imagick.php. – Lokesh Pandey Aug 02 '16 at 19:21

0 Answers0