Image quality based on image size

The only time setting the quality really matters is right before the image is saved or streamed (for the editor). Both of these have the “image_editor_save_pre” filter there, passing it the instance of the image editor. So you can use that to modify the image in any way you like, including setting the quality.

So, something like this should do the job simply and easily:

add_filter('image_editor_save_pre','example_adjust_quality');
function example_adjust_quality($image) {
    $size = $image->get_size();
    // Values are $size['width'] and $size['height']. Based on those, do what you like. Example:
    if ( $size['width'] <= 100 ) {
        $image->set_quality(30);
    }
    if ( $size['width'] > 100 && $size['width'] <= 300 ) {
        $image->set_quality(70);
    }
    if ( $size['width'] > 300 ) {
        $image->set_quality(80);
    }
    return $image;
}

Leave a Comment