Check if a JPEG image has EXIF Orientation tag and rotate it if needed.
Source
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;
}
Hooks
- apply_filters( ‘wp_image_maybe_exif_rotate’,
int $orientation ,string $file ) Filters the
$orientation
value to correct it before rotating or to prevent rotating the image.
Changelog
Version | Description |
---|---|
5.3.0 | Introduced. |
User Contributed Notes
You must log in before being able to contribute a note or feedback.