Table of content
- What is the WebP format for photos?
- Why use the WebP format?
- How to optimize your photos with WebP compression?
- 1 – Use of extensions;
- LiteSpeed Cache
- “Converter for Media – Optimize images | Convert WebP & AVIF”
- 2 – Manually add photos in WebP format;
- 3 – Use custom programming to automate the conversion of your photos;
- How the code works
- Important:
- Conclusion
We recently worked on optimizing a client’s website and saw how the WebP format can make such a difference. In this article, we tell you what it is, how and why to use it. We’ll also give you some tools you can use.
What is the WebP format for photos?
It is an image format created by Google which offers superior photo compression. Via the configuration, you can define at what percentage you want to compress your photo. It is particularly useful for the web as it affects the performance of your website less. As explained in the Google documentation, the size of WebP images is 26% smaller than that of PNG images. By making a comparison with the JPG format, we can estimate 25 to 34%. This gives you an idea of how much it can improve performance. As illustrated by the screenshot below, we have created a code to replace png and jpg formats in WebP format, the result is amazing. If you want to learn more about WebP compression, we recommend Google’s article.
Why use the WebP format?
Considering what we have discussed above, certainly, the use of WebP compression is a plus for your website. Indeed, it significantly reduces the size of your photos (lossy or lossless). It also allows you to have a much faster website and a better user experience. Photos usually have a considerable impact on page load times. However, they are essential to better present its products or services. By optimizing your photos, you can easily reduce the size of images and let your users have a good experience on your website.
How to optimize your photos with WebP compression?
There are several approaches to converting photos to WebP format. Among these approaches is the use of extensions (if you use a content manager). You can also use some online code examples to adapt it to your needs. Another option could manually be to convert your photos before using them.
1 – Use of extensions;
You will find in the library of content managers that you use various extensions to optimize your photos. We particularly used the WordPress extensions that we offer.
LiteSpeed Cache
It is a solution that is available online that you can simultaneously use to optimize your pages and images. You will certainly find it compatible with numerous CMS. In WordPress, there is an option to turn photos into WebP format.
“Converter for Media – Optimize images | Convert WebP & AVIF”
It is an extension with nearly 200,000 downloads available on WordPress. You can detect it by doing the search directly from your extensions tab. Alternatively, go to the wordpress.org website. Depending on the website design software you use, you will find extensions or modules to convert your photos. We recommend that you read the description and conditions before use.
2 – Manually add photos in WebP format;
Several modern website creation software programs accept WebP as a photo format. Alternatively, it is always possible to make adjustments to the configuration or the server. Regarding WordPress, since version 5.8, it is possible to import WebP photos directly. Therefore, it is more than enough to manually convert your photos and import them. For this, you obviously need to use a tool to convert your photos. I will recommend two options:
- Use a software or online tool
- or download a WebP player extension to your computer.
Using online tools can be interesting. However, you should not lose sight of the privacy aspect or the risk of your photos being stolen. The second option is ideal; considering the fact that you can convert your photos directly from your computer before importing them to your website. Below are some examples of applications for converting or using WebP photos on Windows.
3 – Use custom programming to automate the conversion of your photos;
We have found several relatively appealing codes on GitHub that you can use to adapt to your project. Alternatively, you can take inspiration from the php.net documentation to create your code. Our team recently embarked on developing a code to convert all WordPress photos to WebP format. The idea is to make a query in the database. Then list all the photos imported to the site and convert them to WebP. This is rather a success insofar as it considerably allows reducing the loading time while avoiding us to do a manual conversion.
<?php
/**
*
* Photo converter
* */
function webpConvert2($file, $compression_quality = 80)
{
// check if file exists
if (!file_exists($file)) {
return false;
}
$file_type = exif_imagetype($file);
$ddd = str_replace(".png","",$file);
$ddd = str_replace(".jpg","",$ddd);
$ddd = str_replace(".jpeg","",$ddd);
$output_file = $ddd . '.webp';
if (file_exists($output_file)) {
return $output_file;
}
if (function_exists('imagewebp')) {
switch ($file_type) {
case '1': //IMAGETYPE_GIF
$image = imagecreatefromgif($file);
break;
case '2': //IMAGETYPE_JPEG
$image = imagecreatefromjpeg($file);
break;
case '3': //IMAGETYPE_PNG
$image = imagecreatefrompng($file);
imagepalettetotruecolor($image);
imagealphablending($image, true);
imagesavealpha($image, true);
break;
case '6': // IMAGETYPE_BMP
$image = imagecreatefrombmp($file);
break;
case '15': //IMAGETYPE_Webp
return false;
break;
case '16': //IMAGETYPE_XBM
$image = imagecreatefromxbm($file);
break;
default:
return false;
}
// Save the image
$result = imagewebp($image, $output_file, $compression_quality);
if (false === $result) {
return false;
}
// Free up memory
imagedestroy($image);
return $output_file;
} elseif (class_exists('Imagick')) {
$image = new Imagick();
$image->readImage($file);
if ($file_type === "3") {
$image->setImageFormat('webp');
$image->setImageCompressionQuality($compression_quality);
$image->setOption('webp:lossless', 'true');
}
$image->writeImage($output_file);
return $output_file;
}
return false;
}
/**
*
* Insert into table
* */
/**
*
* Convert photo
* */
function psw_photo($attachment_id, $size) {
$para = array();
$fullsize_path = get_attached_file($attachment_id);
$image_attributes = wp_get_attachment_image_src( $attachment_id, $size);
$news = "";
if ( $image_attributes ) :
$data2 = explode("/wp-content/",$fullsize_path);
$data = explode("/wp-content/",$image_attributes[0]);
$absolute = $data2[0]."/wp-content/".$data[1];
$webP = webpConvert2($absolute);
if(!empty($webP)) {
$news = home_url().str_replace($data2[0],'', sanitize_text_field($webP) );
} else {
$news = $image_attributes[0];
}
endif;
return $news;
}
/**
*
* Replace previeous with webp
* */
function update_attachment_filename($post_ID, $image) {
global $wpdb;
$file = $image;
$file_headers = @get_headers($file);
if(!$file_headers || $file_headers[0] == 'HTTP/1.1 404 Not Found') {
}
else {
// Get path to existing attachment
$file = get_attached_file( $post_ID );
$path = pathinfo( $file );
$ddddd = explode("/", $image);
$toa = count($ddddd);
$poart = $ddddd[$toa - 1];
// Create new attachment name
$file_updated = $path['dirname'] . '/' . $poart;
// Update the attachment name
// rename( $file, $file_updated );
update_attached_file( $post_ID, $file_updated );
if ( ! function_exists( 'wp_crop_image' ) ) {
include( ABSPATH . 'wp-admin/includes/image.php' );
}
// Update attachment meta data
$file_updated_meta = wp_generate_attachment_metadata( $post_ID, $file_updated );
// print_r($file_updated_meta);
wp_update_attachment_metadata( $post_ID, $file_updated_meta );
$basename = $path['basename'];
$query1 = "UPDATE $wpdb->postmeta SET meta_value = REPLACE(meta_value,'$basename','$poart');";
$wpdb->query($query1);
$query2 = "UPDATE $wpdb->posts SET post_content = REPLACE(post_content,'$basename','$poart');";
$wpdb->query($query2);
$query3 = "UPDATE $wpdb->posts SET guid = REPLACE(guid,'$basename','$poart');";
$wpdb->query($query3);
$query3 = "UPDATE $wpdb->posts SET post_title = REPLACE(post_title,'$basename','$poart');";
$wpdb->query($query3);
$query4 = "UPDATE $wpdb->postmeta SET meta_value = REPLACE(meta_value,'$basename','$poart') WHERE post_id = $post_ID AND meta_key = '_wp_attached_file' ;";
$wpdb->query($query4);
$url = sanitize_title($poart);
$url2 = sanitize_title($basename);
$my_post = array(
'ID' => $post_ID,
'post_name' => $url,
'post_mime_type' => 'image/webp',
);
// Update the post into the database
wp_update_post( $my_post );
}
}
/**
*
* Process data
* */
function psw_create_converted_version() {
global $wpdb;
if(isset($_GET) && !empty($_GET['cronss']) && strcmp($_GET['cronss'], 'idppdldllglglglgdpd') === 0) {
$query = get_posts( array(
'post_type' => 'attachment',
'orderby' => 'ID',
'order' => 'DESC',
'posts_per_page' => 5,
// 'post_status' => 'inherit',
// 'post_parent' => 61682,
'meta_query' => array(
array(
'key' => 'already_converted_pictures',
'compare' => 'NOT EXISTS' // this should work...
),
)
) );
$sizes = array("full");
$attachments = $query;
if ( $attachments ) {
foreach ( $attachments as $post ) {
$image_attributes = wp_get_attachment_image_src($post->ID);
$id = $post->ID;
$image_attributes = wp_get_attachment_image_src( $id );
if ( $image_attributes ) :
if (strpos($image_attributes[0], '.webp') === false) {
$new = psw_photo($id, "full");
update_attachment_filename($id, $new);
echo $new, " ", $image_attributes[0], "<br/>";
}
endif;
add_post_meta($id, 'already_converted_pictures', 'red', true );
}
}
exit;
}
}
add_action('init', 'psw_create_converted_version', 1000);
How the code works
You can code the file in your current theme and use the WordPress “include” function to add it to your functions.php file. We use a cron job to run the code. This allows you not to have to spend time repeating the same actions. Simultaneously, we added a parameter that helps identify when the code should run. Bulk. If you include the code in your functions.php file and use the link below, you will be able to do the conversion.
Important:
- We recommend that you use the code with caution. Indeed, we tested it on three websites. But, this does not guarantee that it will work on all websites.
Conclusion
You have all the tools you need to optimize your images. Whether you are a web development hobbyist, an expert, or a business owner, you can choose the options that fit your needs. If you are keen to work with experts in creating bespoke websites, contact us.
Leave a comments: