WordPress.org

Make WordPress Core


Ignore:
Timestamp:
05/04/2021 02:43:36 PM (7 months ago)
Author:
adamsilverstein
Message:

Images: enable WebP support.

Add support for uploading, editing and saving WebP images when supported by the server.

Add 'image/webp' to supported mime types. Correctly identify WebP images and sizes even when PHP doesn't support WebP. Resize uploaded WebP files (when supported) and use for front end markup.

Props markoheijne, blobfolio, Clorith, joemcgill, atjn, desrosj, spacedmonkey, marylauc, mikeschroder, hellofromtonya, flixos90.
Fixes #35725.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/class-wp-image-editor-gd.php

    r50146 r50810  
    7070            case 'image/gif':
    7171                return ( $image_types & IMG_GIF ) != 0;
     72            case 'image/webp':
     73                return ( $image_types & IMG_WEBP ) != 0; // phpcs:ignore PHPCompatibility.Constants.NewConstants.img_webpFound
    7274        }
    7375
     
    100102        }
    101103
    102         $this->image = @imagecreatefromstring( $file_contents );
     104        // WebP may not work with imagecreatefromstring().
     105        if (
     106            function_exists( 'imagecreatefromwebp' ) &&
     107            ( 'image/webp' === wp_get_image_mime( $this->file ) )
     108        ) {
     109            $this->image = @imagecreatefromwebp( $this->file );
     110        } else {
     111            $this->image = @imagecreatefromstring( $file_contents );
     112        }
    103113
    104114        if ( ! is_gd_image( $this->image ) ) {
     
    458468        } elseif ( 'image/jpeg' === $mime_type ) {
    459469            if ( ! $this->make_image( $filename, 'imagejpeg', array( $image, $filename, $this->get_quality() ) ) ) {
     470                return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) );
     471            }
     472        } elseif ( 'image/webp' == $mime_type ) {
     473            if ( ! function_exists( 'imagewebp' ) || ! $this->make_image( $filename, 'imagewebp', array( $image, $filename, $this->get_quality() ) ) ) {
    460474                return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) );
    461475            }
     
    503517                header( 'Content-Type: image/gif' );
    504518                return imagegif( $this->image );
     519            case 'image/webp':
     520                if ( function_exists( 'imagewebp' ) ) {
     521                    header( 'Content-Type: image/webp' );
     522                    return imagewebp( $this->image, null, $this->get_quality() );
     523                }
     524                // Fall back to the default if webp isn't supported.
    505525            default:
    506526                header( 'Content-Type: image/jpeg' );
Note: See TracChangeset for help on using the changeset viewer.