Update: I just found there was a Nginx/Apache module PageSpeed that support WebP, you may try it in my site here, and here you may notice that some pictures were loaded from a .webp source. The module for Nginx called ngx_pagespeed, could load pictures conditionally in .webp or normal .png/.jpg/.gif formates. But seems this module has a high CPU and Memory occupation, you got to trade-off between speed and performance.


WebP is a Google developed modern image format that provides superior lossless and lossy compression for images on the web. Compired to shrunk images that processed by tools like TinyPNG, WebP images cloud be more tiny (how tiny it is? See here). But currently, the biggest problem is few browsers support WebP.

WebP_Support.png

So if you are going to work with WebP images, you'd better consider compatibility with (mainly) none-chromium based browsers.

My idea is detecting the browser supported content types by accept in HTTP Resuest Headers:

webp.png
So seems this brower support WebP

Now you may detect whether user support WebP with PHP, and response with different content types:

if(strpos($_SERVER['HTTP_ACCEPT'], 'image/webp')) {
    // Something to do with WebP supported
    header('Content-Type: image/webp');
} else {
    // When WebP is not supported
    header('Content-Type: image/PNG');
}

Another problem, how to convert normal png/jpg/jpeg/gif images to WebP? Seems WebP is not supported well in PHP, so I convert images to WebP type with a Python script:

(pillow lib is necessary: pip3 install pillow)

#coding=utf-8
from PIL import Image
import os
from os import listdir
from os.path import isfile, join

# Do not forget the '/'
mypath = 'png/' # Your png/jpg/jpeg/gif folder path
webp_path = 'webp/' # WebP output path

def convert_to_webp(filename):
    im = Image.open(mypath + filename).convert("RGB")
    im.save(webp_path + filename + ".webp", "WEBP")

# Get a list of all file names
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]

for f in onlyfiles:
    convert_to_webp(f)

If you hope to do it automatically, you may consider call Python script with PHP like this:

<?php 

$command = escapeshellcmd('/usr/custom/test.py');
$output = shell_exec($command);
echo $output;

?>

You may see my WebP API demo here (Chrmoe is necessary): https://api.shino.cc/webp

Q.E.D.

Comments