Reduce image quality on the fly and display lower quality version

I have a competition website that uses WordPress allowing users to submit images. There are 700+ entries with up to 6 images each, with a maximum filesize of 3mb for each image.

I’ve then listed all the entries as posts, then on each post it displays the images.

Read More

Each image is displayed using the_field('image1');, the_field('image2');, the_field('image3'); etc.

The problem I have is that the page is then trying to load 6 images at 3mb’s a time. Is there a way to optimise the image on the fly and show it at 50% quality?

Related posts

Leave a Reply

4 comments

  1. You can resize the picture on the fly after extracting it from a database (or file) without having to create another temporary file. Presumably you have a URL which gets an image from the database.

    $pdo = new PDO("somewhere");
    $sql = "SELECT image_data FROM pictures WHERE id=1";
    
    $stmt = $pdo->query( $sql );
    $obj = $stmt->fetch(PDO::FETCH_OBJ);
    
    $img = imagecreatefromstring($obj->image_data);
    
    header('Content-Type: image/jpeg');
    imagejpeg($img, NULL, 50);
    
    imagedestroy($img);
    

    If you pass NULL as a file name to imagejpeg it will write the jpeg to standard out. The 3rd parameter is the quality level, in this case 50%.

  2. $file =  $_GET['file'];//URL with img parameter http://localhost/fk/test.php?file=1.jpeg
    $quality = 40; //Change What quality you needed
    $location = "images/".$file;
    $image = imagecreatefromjpeg($file);
    imagejpeg($image, $location, $quality) ;
    header('Content-Type: image/jpeg');
        header('Content-Length: ' . filesize($location));
        header('Content-Disposition: inline; filename="'.$file.'"');
        echo file_get_contents($location);
    
  3. There is no way to resize images on the fly. There is only straight way to make CPU choke with such a denial-of-service self-attack.

    Images have to be pre-resized to reasonable size and quality right after upload. Every web-site in the world does it this way.