1

We are currently using this to change the compression used on jpgs when uploaded to the WP media library:

add_filter(‘jpeg_quality’, function($arg){return 75;});

However, this does not compress the original image. We sometimes need to display the original image on our website and this also needs to be compressed. How do we do this?

Thanks in advance for any help!

2
  • Thumbnail add_image_size PNG not working
    – Litalino
    Commented Aug 7, 2023 at 3:02
  • @Litalino I converted this from an answer into a comment, but I couldn't tell if you were replying to the question or towebtours answer? If you have a new question you should click the ask question button, this isn't a messageboard/forum so you shouldn't look for the closest question to your problem and try to continue discussion
    – Tom J Nowell
    Commented Aug 7, 2023 at 11:35

1 Answer 1

2

For compressing the uploaded image I wrote a simple code snippet that immediately overwrites a newly uploaded file with an image whose quality can be specified:

function wt_handle_upload_callback( $data ) {
    $image_quality = 30; // Change this according to your needs
    $file_path = $data['file'];
    $image = false;

    switch ( $data['type'] ) {
        case 'image/jpeg': {
            $image = imagecreatefromjpeg( $file_path );
            imagejpeg( $image, $file_path, $image_quality );
            break;          
        }

        case 'image/png': {
            $image = imagecreatefrompng( $file_path );
            imagepng( $image, $file_path, $image_quality );
            break;          
        }

        case 'image/gif': {         
            // Nothing to do here since imagegif doesn't have an 'image quality' option
            break;
        }
    }

    return $data;
}
add_filter( 'wp_handle_upload', 'wt_handle_upload_callback' );

Regarding the additional image sizes (just change the return value):

add_filter( 'wp_editor_set_quality', function( $quality ) { return 30; } );
2
  • This is great code snippet. BUT, on my tests, this function removes all image EXIF/IPTC data too. Can you please modify it to have option to preserve image EXIF data? than I will use it for sure. Thank you @webtoure Commented Jan 13, 2016 at 10:05
  • Thanks! This solution works and should be marked as solution. Commented Nov 24, 2019 at 14:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.