Sunday, September 4, 2022
HomeWordPress Developmentoptimization - Serve photos as webp if browser assist

optimization – Serve photos as webp if browser assist


I need to serve webp photos if the browser assist as Google Web page Pace is asking me to serve photos in next-gen format ,
I’m searching for an answer with out utilizing any plugin :

I’ve discovered some code snippets which may be useful :

Convert Picture to webp format :

<?php

// Picture
$dir="img/nations/";
$title="brazil.png";
$newName="brazil.webp";

// Create and save
$img = imagecreatefrompng($dir . $title);
imagepalettetotruecolor($img);
imagealphablending($img, true);
imagesavealpha($img, true);
imagewebp($img, $dir . $newName, 100);
imagedestroy($img);

From Php Official Documentation

I’ve additionally discovered this code for optimization that is perhaps helpful

/**
 * B) Modify the standard of unique jpeg photos to 90, throughout uploads
 */
add_filter( 'wp_generate_attachment_metadata', perform( $metadata, $attachment_id )
{
    $file = get_attached_file( $attachment_id );
    $sort = get_post_mime_type( $attachment_id );

    // Goal jpeg photos
    if( in_array( $sort, [ 'image/jpg', 'image/jpeg' ] ) )
    {
        // Test for a sound picture editor
        $editor = wp_get_image_editor( $file );
        if( ! is_wp_error( $editor ) )
        {
            // Set the brand new picture high quality
            $consequence = $editor->set_quality( 90 );

            // Re-save the unique picture file
            if( ! is_wp_error( $consequence ) )
                $editor->save( $file );
        }
    }
    return $metadata;
}, 10, 2 );

I’ve googled about this lots however I’ve discovered solely options primarily based on plugins .
Do anybody has any thought about that ?
Thanks prematurely

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments