A) We could therefore use something like the following, to modify the quality of the original jpeg image file to(to e.g. 90%90) during uploads:
/**
* A) Modify the quality of original jpeg images to 90%90, during uploads
*/
add_filter( 'wp_handle_upload', function( $data )
{
if( ! isset( $data['file'] ) || ! isset( $data['type'] ) )
return $data;
// Target jpeg images
if( in_array( $data['type'], [ 'image/jpg', 'image/jpeg' ] ) )
{
// Check for a valid image editor
$editor = wp_get_image_editor( $data['file'] );
if( ! is_wp_error( $editor ) )
{
// Set the new image quality
$result = $editor->set_quality( 90 );
// Re-save the original image file
if( ! is_wp_error( $result ) )
$editor->save( $data['file'] );
}
}
return $data;
} );
B) If we take a look at the media_handle_upload()
function, we might consider hooking into the wp_generate_attachment_metadata
filter instead, to modify the original jpeg image file, after the intermediate sizes have been generated.
/**
* B) Modify the quality of original jpeg images to 90%90, during uploads
*/
add_filter( 'wp_generate_attachment_metadata', function( $metadata, $attachment_id )
{
$file = get_attached_file( $attachment_id );
$type = get_post_mime_type( $attachment_id );
// Target jpeg images
if( in_array( $type, [ 'image/jpg', 'image/jpeg' ] ) )
{
// Check for a valid image editor
$editor = wp_get_image_editor( $file );
if( ! is_wp_error( $editor ) )
{
// Set the new image quality
$result = $editor->set_quality( 90 );
// Re-save the original image file
if( ! is_wp_error( $result ) )
$editor->save( $file );
}
}
return $metadata;
}, 10, 2 );
Update: Just did some simple testing with an image of our kitchen wall clock. Here we can see that when the full size image is re-saved at %1, with quality 5, then all the intermediate sizes (300x200 and 150x150) in: