WordPress上传图片自动添加webp格式文件
  • 3年前
  • WordPress上传图片自动添加webp格式文件617
  • webp格式的图片有点我就不说了,不明白的可以看看下面的描述: [list title="" type="" unique_number="list_1c0476bde9d04899a71b03e4e2eeeb8e"] WebP,是一种同时提供了有损压缩与无损压缩的图片文件格式,派生自视频编码格式 VP8。WebP 最初在2010年发布,目标是减少文件大小,但达到 和 JEPG 格式相同的图片质量,希望能够减少图片档在网络上的发送时间。2011年11月8日,Google 开始让 WebP 支持无损压缩和透明色的功能。 [/list]

    现在很多站点已经开始使用这个格式的图片作为主力,但是我个人还是比较推荐保留两种格式,毕竟不是所有人都喜欢webp格式的文件,同时存在源文件格式和webp格式文件才是最优解,毕竟现在的硬盘空间已经不值钱了。

    看了上面的所有说明,你没有顾虑,可以看看下面的代码:

    WP GD Image Engine If the file is deleted form the Media Library the created WebP conversions will also be deleted.
    * Version: 1.0.0
    * Requires at least: 5.5
    * Requires PHP: 7.2
    * Author: lowtechsun
    * Author URI: https://stackoverflow.com/users/1010918/lowtechsun
    * License: GPL v2 or later
    * License URI: https://www.gnu.org/licenses/gpl-2.0.html
    */
    
    //=================================================
    // Security: Abort if this file is called directly
    //=================================================
    if ( ! defined( 'ABSPATH' ) ) {
        die;
    }
    
    function debug( $info ) {
        $message = null;
    
        if ( is_string( $info ) || is_int( $info ) || is_float( $info ) ) {
            $message = $info;
        } else {
            $message = var_export( $info, true );
        }
    
        if ( $fh = fopen( ABSPATH . '/gdwebpconvert.log', 'a' ) ) {
            fputs( $fh, date( 'Y-m-d H:i:s' ) . " $message\n" );
            fclose( $fh );
        }
    }
    
    add_filter( 'wp_generate_attachment_metadata', 'gd_webp_converter', 10, 2 );
    
    function gd_webp_converter( $metadata, $attachment_id ) {
    
        $gd_webp_converter = new GDWebPConverter( $attachment_id );
        $gd_webp_converter->check_file_exists( $attachment_id );
        $gd_webp_converter->check_mime_type();
        $gd_webp_converter->create_array_of_sizes_to_be_converted( $metadata );
        $gd_webp_converter->convert_array_of_sizes();
    
        return $metadata;
    }
    
    class GDWebPConverter {
    
        private $file_path;
        private $file_dirname;
        private $file_ext;
        private $file_name_no_ext;
    
        private $array_of_sizes_to_be_converted = array();
        private $array_of_sizes_to_be_deleted   = array();
    
        public function __construct( $attachment_id ) {
    
            $this->file_path = get_attached_file( $attachment_id );
            debug( $this->file_path );
    
            // https://stackoverflow.com/questions/2183486/php-get-file-name-without-file-extension/19040276
            $this->file_dirname = pathinfo( $this->file_path, PATHINFO_DIRNAME );
            debug( $this->file_dirname );
    
            $this->file_ext = strtolower( pathinfo( $this->file_path, PATHINFO_EXTENSION ) );
            debug( $this->file_ext );
    
            $this->file_name_no_ext = pathinfo( $this->file_path, PATHINFO_FILENAME );
            debug( $this->file_name_no_ext );
        }
    
        public function check_file_exists( $attachment_id ) {
    
            $file = get_attached_file( $attachment_id );
    
            if ( ! file_exists( $file ) ) {
                $message = 'The uploaded file does not exist on the server. Encoding not possible.';
                debug( $message );
                throw new Exception( 'The uploaded file does exist on the server. Encoding not possible.', 1 );
            }
    
        }
    
        public function check_mime_type() {
    
            // https://www.php.net/manual/en/function.finfo-file.php
            $finfo = finfo_open( FILEINFO_MIME_TYPE );
    
            $this->file_mime_type = finfo_file( $finfo, $this->file_path );
    
            finfo_close( $finfo );
            // debug( $this->file_mime_type );
    
            // https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
            $this->allowed_mime_type = array( 'image/jpeg', 'image/png' );
    
            if ( ! in_array( $this->file_mime_type, $this->allowed_mime_type, true ) ) {
    
                $message = 'MIME type of file not supported';
                // debug( $message );
                throw new Exception( 'MIME type of file not supported', 1 );
    
            }
        }
    
        public function create_array_of_sizes_to_be_converted( $metadata ) {
    
            // push original file to the array
            array_push( $this->array_of_sizes_to_be_converted, $this->file_path );
            // debug( $this->array_of_sizes_to_be_converted );
    
            // push all created sizes of the file to the array
            foreach ( $metadata['sizes'] as $value ) {
                // debug( $value['file'] );
                array_push( $this->array_of_sizes_to_be_converted, $this->file_dirname . '/' . $value['file'] );
            }
            // // debug( $this->array_of_sizes_to_be_converted );
        }
    
        public function convert_array_of_sizes() {
    
            debug( $this->array_of_sizes_to_be_converted );
    
            switch ( $this->file_ext ) {
                case 'jpeg':
                case 'jpg':
                    foreach ( $this->array_of_sizes_to_be_converted as $key => $value ) {
    
                        $image = imagecreatefromjpeg( $value );
    
                        if ( 0 === $key ) {
    
                            imagewebp( $image, $this->file_dirname . '/' . $this->file_name_no_ext . '.webp', 80 );
    
                        } else {
    
                            $current_size = getimagesize( $value );
                            // debug( $current_size );
                            imagewebp( $image, $this->file_dirname . '/' . $this->file_name_no_ext . '-' . $current_size[0] . 'x' . $current_size[1] . '.webp', 80 );
    
                        }
    
                        imagedestroy( $image );
                    }
                    break;
    
                case 'png':
                    foreach ( $this->array_of_sizes_to_be_converted as $key => $value ) {
    
                        $image = imagecreatefrompng( $value );
                        imagepalettetotruecolor( $image );
                        imagealphablending( $image, true );
                        imagesavealpha( $image, true );
    
                        if ( 0 === $key ) {
    
                            imagewebp( $image, $this->file_dirname . '/' . $this->file_name_no_ext . '.webp', 80 );
    
                        } else {
    
                            $current_size = getimagesize( $value );
                            // debug( $current_size );
                            imagewebp( $image, $this->file_dirname . '/' . $this->file_name_no_ext . '-' . $current_size[0] . 'x' . $current_size[1] . '.webp', 80 );
    
                        }
    
                        imagedestroy( $image );
    
                    }
                    break;
    
                // animated GIF to WebP not supported by GD - imagecreatefromgif
                // case 'gif':
                //  foreach ( $this->array_of_sizes_to_be_converted as $key => $value ) {
    
                //      $image = imagecreatefromgif( $value );
    
                //      if ( 0 === $key ) {
    
                //          imagewebp( $image, $this->file_dirname . '/' . $this->file_name_no_ext . '.webp', 80 );
    
                //      } else {
    
                //          $current_size = getimagesize( $value );
                //          // debug( $current_size );
                //          imagewebp( $image, $this->file_dirname . '/' . $this->file_name_no_ext . '-' . $current_size[0] . 'x' . $current_size[1] . '.webp', 80 );
    
                //      }
    
                //      imagedestroy( $image );
    
                //  }
                //  break;
    
                default:
                    return false;
            }
    
        }
    
        public function create_array_of_sizes_to_be_deleted( $attachment_id ) {
    
            // debug( $attachment_id );
    
            $this->attachment_metadata_of_file_to_be_deleted = wp_get_attachment_metadata( $attachment_id );
            // debug( $this->attachment_metadata_of_file_to_be_deleted );
    
            // push original file to the array
            array_push( $this->array_of_sizes_to_be_deleted, $this->file_dirname . '/' . $this->file_name_no_ext . '.webp' );
            // debug( $this->array_of_sizes_to_be_converted );
    
            // push all created sizes of the file to the array
            foreach ( $this->attachment_metadata_of_file_to_be_deleted['sizes'] as $value ) {
    
                // debug( $value );
    
                $this->value_file_name_no_ext = pathinfo( $value['file'], PATHINFO_FILENAME );
                // debug( $this->value_file_name_no_ext );
    
                array_push( $this->array_of_sizes_to_be_deleted, $this->file_dirname . '/' . $this->value_file_name_no_ext . '.webp' );
            }
            // debug( $this->array_of_sizes_to_be_deleted );
        }
    
        public function delete_array_of_sizes() {
    
            debug( $this->array_of_sizes_to_be_deleted );
    
            foreach ( $this->array_of_sizes_to_be_deleted as $key => $value ) {
    
                // debug( $value );
                unlink( $value );
    
            }
        }
    
    }
    
    add_action( 'delete_attachment', 'delete_webp_conversions', 10 );
    
    function delete_webp_conversions( $attachment_id ) {
    
        $delete_webp_conversions = new GDWebPConverter( $attachment_id );
        $delete_webp_conversions->create_array_of_sizes_to_be_deleted( $attachment_id );
        $delete_webp_conversions->delete_array_of_sizes();
    
    }
    

    代码方面来自: https://stackoverflow.com/questions/67183333/wordpress-convert-image-to-webp-format-programmatically-with-gd-image-engine

    经过测试之后,上传图片确实是可以在后台生成对应的webp图片,效果截图如下:

    同样的,你可以尝试一下,上方的图片修改后缀为webp同样可以看到图片。

    上面的代码直接保存为一个php文件之后,在function文件中通过include导入即可完成该功能。 [hong unique_number="hong_c7763c9c91264932b1f2339b58d88053"] 经过尝试,这里需要注意的就是PHP方面需要开启fileinfo扩展,否则会报错,报错内容大概为:Call to undefined function finfo_open() [/hong]

  • 联系我们
  • 有任何疑问欢迎联系我们
  • WP新手学园
  • WordPress上传图片自动添加webp格式文件
  • 邮箱:2830776172#qq.com(#换成@)
  • 回复时间:9:00-19:00
  • 如果提问.请图文并茂,详细描述问题
  • WordPress上传图片自动添加webp格式文件
  • 微信号:wpxsxy_official
  • 仅支持付费解决问题
  • *并非所有问题都会被回复
  • WordPress上传图片自动添加webp格式文件
  • QQ:2830776172
  • 回复时间:9:00-19:00
  • QQ仅支持付费提问,时间有限,尽情谅解
  • WordPress上传图片自动添加webp格式文件
  • QQ群:198768181
  • 有问题可以进去提问,寻求群友帮助
  • *并非所有问题都会被回复
  • WordPress上传图片自动添加webp格式文件
  • 咸鱼:WP新手学园
  • 如果对于直接交易不放心,可以走闲鱼
  • *咸鱼价格不作为最终交易价格
  • 备案号:鄂ICP备2021011647号-1