optimization – Serve images as webp if browser support

Question

I want to serve webp images if the browser support as Google Page Speed is asking me to serve images in next-gen format ,
I am looking for a solution without using any plugin :

I have found some code snippets that may be helpful :

Convert Image to webp format :

<?php

// Image
$dir="img/countries/";
$name="brazil.png";
$newName="brazil.webp";

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

From Php Official Documentation

I have also found this code for optimization that might be useful

/**
 * B) Modify the quality of original jpeg images to 90, during uploads
 */
add_filter( 'wp_generate_attachment_metadata', function( $metadata, $attachment_id )
{
    $file = get_attached_file( $attachment_id );
    $type = get_post_mime_type( $attachment_id );

    // Target jpeg images
    if( in_array( $type, [ 'image/jpg', 'image/jpeg' ] ) )
    {
        // Check for a valid image editor
        $editor = wp_get_image_editor( $file );
        if( ! is_wp_error( $editor ) )
        {
            // Set the new image quality
            $result = $editor->set_quality( 90 );

            // Re-save the original image file
            if( ! is_wp_error( $result ) )
                $editor->save( $file );
        }
    }
    return $metadata;
}, 10, 2 );

I have googled about this a lot but I have found only solutions based on plugins .
Do anyone has any idea about that ?
Thanks in advance

0
Ahmed C 3 weeks 2022-09-03T18:55:18-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse