Determines the encode quality WordPress would use for an image.
Description
Resolves the quality the same way WP_Image_Editor::set_quality() does when no explicit quality is supplied: it starts from the per-format default, applies the ‘wp_editor_set_quality’ filter, then the ‘jpeg_quality’ filter for JPEG output, resets out-of-range values to the per-format default, and squashes 0 to 1.
This lets code outside of an image editor instance – such as the REST API, which reports the quality client-side processing should use – resolve the same value the server would apply, without loading the image into an editor.
Parameters
$mime_typestringrequired- The output image MIME type, e.g.
'image/jpeg'. $sizearrayoptional- Dimensions of the image, passed to the ‘wp_editor_set_quality’ filter.
widthintThe image width in pixels.heightintThe image height in pixels.
Default:
array() $default_qualityint|nulloptional- Starting quality before filters are applied.
Defaults to the per-format default (86 for WebP, 82 otherwise).Default:
null
Source
function wp_get_image_encode_quality( string $mime_type, array $size = array(), ?int $default_quality = null ): int {
if ( null === $default_quality ) {
// Mirror WP_Image_Editor::get_default_quality(): WebP defaults to 86, everything else to 82.
$default_quality = ( 'image/webp' === $mime_type ) ? 86 : 82;
}
/** This filter is documented in wp-includes/class-wp-image-editor.php */
$quality = apply_filters( 'wp_editor_set_quality', $default_quality, $mime_type, $size );
if ( 'image/jpeg' === $mime_type ) {
/** This filter is documented in wp-includes/class-wp-image-editor.php */
$quality = apply_filters( 'jpeg_quality', $quality, 'image_resize' );
}
if ( ! is_numeric( $quality ) ) {
$quality = $default_quality;
} else {
$quality = (int) $quality;
}
// Reset out-of-range values to the default, matching WP_Image_Editor::set_quality().
if ( $quality < 0 || $quality > 100 ) {
$quality = $default_quality;
}
// Allow 0, but squash to 1, matching WP_Image_Editor::set_quality().
if ( 0 === $quality ) {
$quality = 1;
}
return $quality;
}
Hooks
- apply_filters( ‘jpeg_quality’,
int $quality ,string $context ) Filters the JPEG compression quality for backward-compatibility.
- apply_filters( ‘wp_editor_set_quality’,
int $quality ,string $mime_type ,array $size ) Filters the default image compression quality setting.
Changelog
| Version | Description |
|---|---|
| 7.1.0 | Introduced. |
User Contributed Notes
You must log in before being able to contribute a note or feedback.