Skip to main content
1 of 6
birgire
  • 67.8k
  • 7
  • 119
  • 251

A workaround by extending the WP_Image_Editor_GD class

Note that the image_resize() function is deprecated and it's for example used as a callback for the jpeg_quality filter:

$quality = apply_filters( 'jpeg_quality', $quality, 'image_resize' );

I'm sure this callback will be replaced soon with the relevant resize method.

But we could also use the wp_editor_set_quality filter to change the quality of intermediate jpeg image sizes.

Here's one idea:

add_filter( 'jpeg_quality', function( $quality ) {
    add_filter( 'wpse_make_image_arguments', 
        function( $arguments, $filename, $function, $size ) {       

            // --------------------------------------------
            // Extract the width/height from the $size 
            // and modify the quality settings in $arguments[2] accordingly:
            if( isset($size['height']) && isset($size['width']) && isset($arguments[2]) ){  
                // Modify this part to your needs:
                if( $size['height'] <= 150  && $size['width'] <= 150 ) {
                    $arguments[2] = '50' 
                }
            }
            // --------------------------------------------

            return $arguments;
        }, 10, 4 );
    return $quality;
} );

where we've extended the WP_Image_Editor_GD class:

add_filter( 'wp_image_editors', function( $editors ) {
    // Note that the WP_Image_Editor_GD and WP_Image_Editor_Imagick classes
    // are included within this filter. So let's do the same for our extension class.

    // Our extended class:
    class WP_Image_Editor_GD_WPSE extends WP_Image_Editor_GD
    {
        protected function make_image( $filename, $function, $arguments ) {
            if ( wp_is_stream( $filename ) )
                $arguments[1] = null;

            // Add a custom filter:             
            $arguments = apply_filters( 'wpse_make_image_arguments', 
                $arguments, $filename, $this->size, $function );
            return parent::make_image( $filename, $function, $arguments );
        }
    }
    // Prepend the extended class to the array of image editors:    
    array_unshift( $editors, 'WP_Image_Editor_GD_WPSE' );
    return $editors;
} );

where we introduced the custom wpse_make_image_arguments filter.

This way we can modify the quality settings, before the intermediate files are saved.

PS: I didn't check out the case when the Imagick library is used instead, but I guess we could do something similar by extending the WP_Image_Editor_Imagick class.

birgire
  • 67.8k
  • 7
  • 119
  • 251