PluginProbe
Image Optimization – Compress Images and Convert to WebP or AVIF / 1.6.8
Image Optimization – Compress Images and Convert to WebP or AVIF v1.6.8
1.7.6 1.7.5 1.7.4 trunk 1.0.0 1.0.1 1.0.2 1.1.0 1.2.0 1.2.1 1.3.0 1.4.0 1.4.1 1.5.0 1.5.1 1.5.2 1.5.3 1.5.4 1.6.0 1.6.1 1.6.2 1.6.3 1.6.4 1.6.5 1.6.6 All 32 releases
image-optimization / modules / optimization / components / avif-compatibility.php

avif-compatibility.php in Image Optimization – Compress Images and Convert to WebP or AVIF 1.6.8, at modules/optimization/components/avif-compatibility.php

83 lines 2.1 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace ImageOptimization\Modules\Optimization\Components;
4
5 use ImageOptimization\Classes\Image\Image_Dimensions;
6
7 if ( ! defined( 'ABSPATH' ) ) {
8 exit; // Exit if accessed directly.
9 }
10 class Avif_Compatibility {
11 public function is_avif_supported(): bool {
12 return in_array( 'image/avif', get_allowed_mime_types(), true );
13 }
14
15 public function add_to_supported_types( $mime_types ) {
16 $mime_types['avif'] = 'image/avif';
17 return $mime_types;
18 }
19
20 public function add_to_supported_mime_types( $mime_types ) {
21 $mime_types['image/avif'] = 'avif';
22 return $mime_types;
23 }
24
25 public function mark_as_displayable( $result, $path ) {
26 if ( str_ends_with( $path, '.avif' ) ) {
27 return true;
28 }
29
30 return $result;
31 }
32
33 public function fix_avif_images( $metadata, $attachment_id ) {
34 if ( empty( $metadata ) ) {
35 return $metadata;
36 }
37
38 $attachment = get_post( $attachment_id );
39
40 if ( ! $attachment || is_wp_error( $attachment ) || 'image/avif' !== $attachment->post_mime_type ) {
41 return $metadata;
42 }
43
44 if ( ( ! empty( $metadata['width'] ) && ( 0 !== $metadata['width'] ) ) && ( ! empty( $metadata['height'] ) && 0 !== $metadata['height'] ) ) {
45 return $metadata;
46 }
47
48 $file = get_attached_file( $attachment_id );
49
50 if ( ! $file ) {
51 return $metadata;
52 }
53
54 $dimensions = Image_Dimensions::get_by_path( $file );
55
56 $metadata['width'] = $dimensions->width;
57 $metadata['height'] = $dimensions->height;
58
59 if ( empty( $metadata['file'] ) ) {
60 $metadata['file'] = _wp_relative_upload_path( $file );
61 }
62
63 if ( empty( $metadata['sizes'] ) ) {
64 $metadata['sizes'] = [];
65 }
66
67 return $metadata;
68 }
69
70 public function __construct() {
71 if ( $this->is_avif_supported() ) {
72 return;
73 }
74
75 add_filter( 'upload_mimes', [ $this, 'add_to_supported_types' ] );
76 add_filter( 'mime_types', [ $this, 'add_to_supported_types' ] );
77 add_filter( 'getimagesize_mimes_to_exts', [ $this, 'add_to_supported_mime_types' ] );
78 add_filter( 'file_is_displayable_image', [ $this, 'mark_as_displayable' ], 10, 2 );
79
80 add_filter( 'wp_generate_attachment_metadata', [ $this, 'fix_avif_images' ], 1, 3 );
81 }
82 }
83