wp_get_image_encode_quality()WP 7.1.0

Determines the encode quality WordPress would use for an image.

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 then the jpeg_quality 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.

Hooks from the function

Returns

int. Encode quality between 1 and 100.

Usage

wp_get_image_encode_quality( $mime_type, $size, ?int $default_quality ): int;
$mime_type(string) (required)
The output image MIME type, e.g. 'image/jpeg'.
$size(array)

Dimensions of the image, passed to the wp_editor_set_quality

Default: array()

  • width(int)
    The image width in pixels.

  • height(int)
    The image height in pixels.
?int $default_quality
.
Default: null

Changelog

Since 7.1.0 Introduced.

wp_get_image_encode_quality() code WP 7.1

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;
}