WP_Image_Editor::maybe_exif_rotate()publicWP 5.3.0

Check if a JPEG image has EXIF Orientation tag and rotate it if needed.

Method of the class: WP_Image_Editor{}

Hooks from the method

Return

true|false|WP_Error. True if the image was rotated. False if not rotated (no EXIF data or the image doesn't need to be rotated). WP_Error if error while rotating.

Usage

$WP_Image_Editor = new WP_Image_Editor();
$WP_Image_Editor->maybe_exif_rotate();

Changelog

Since 5.3.0 Introduced.

WP_Image_Editor::maybe_exif_rotate() code WP 6.6.2

public function maybe_exif_rotate() {
	$orientation = null;

	if ( is_callable( 'exif_read_data' ) && 'image/jpeg' === $this->mime_type ) {
		$exif_data = @exif_read_data( $this->file );

		if ( ! empty( $exif_data['Orientation'] ) ) {
			$orientation = (int) $exif_data['Orientation'];
		}
	}

	/**
	 * Filters the `$orientation` value to correct it before rotating or to prevent rotating the image.
	 *
	 * @since 5.3.0
	 *
	 * @param int    $orientation EXIF Orientation value as retrieved from the image file.
	 * @param string $file        Path to the image file.
	 */
	$orientation = apply_filters( 'wp_image_maybe_exif_rotate', $orientation, $this->file );

	if ( ! $orientation || 1 === $orientation ) {
		return false;
	}

	switch ( $orientation ) {
		case 2:
			// Flip horizontally.
			$result = $this->flip( false, true );
			break;
		case 3:
			/*
			 * Rotate 180 degrees or flip horizontally and vertically.
			 * Flipping seems faster and uses less resources.
			 */
			$result = $this->flip( true, true );
			break;
		case 4:
			// Flip vertically.
			$result = $this->flip( true, false );
			break;
		case 5:
			// Rotate 90 degrees counter-clockwise and flip vertically.
			$result = $this->rotate( 90 );

			if ( ! is_wp_error( $result ) ) {
				$result = $this->flip( true, false );
			}

			break;
		case 6:
			// Rotate 90 degrees clockwise (270 counter-clockwise).
			$result = $this->rotate( 270 );
			break;
		case 7:
			// Rotate 90 degrees counter-clockwise and flip horizontally.
			$result = $this->rotate( 90 );

			if ( ! is_wp_error( $result ) ) {
				$result = $this->flip( false, true );
			}

			break;
		case 8:
			// Rotate 90 degrees counter-clockwise.
			$result = $this->rotate( 90 );
			break;
	}

	return $result;
}