Code

Coding, Programming & Algorithms, Tips, Tweaks & Hacks
Search

Sponsored Ads

Using WebP image format for browsers that support it

The WebP image format for the web is starting to get a lot of hype for its massive file compression. Chrome supports it since ver 9 and Opera since ver 11.10.
Image file sizes are reduced by more than 50% in WebPs when compared to JPGs.
Looking at Google Analytics on various sites, Chrome 9+ users constitute 20% - 25%. So providing one-fifth or one-fourth of the users with a much reduced page load is worth the extra effort.

1. Convert JPGs / PNGs to WebPs :

for i in *.jpg; do j=`echo "$i" | cut -d . -f 1`; convert -colorspace RGB "$i" "$i"; ~/libwebp/cwebp -q 75 "$i" -o "${j}.webp"; done

convert is used to convert the colourspace from RGB to CMYK since as of now, webp encoder doesn't support CMYK colourspace.

2. Use 2 different CSS files for background images - one for standard jpg/png and another for webp. Chrome 9+ and Opera 11.10+ would be served webp.css while all others img.css.

get_browser is pretty useful for browser detection, but requires to set browscap in php.ini which is a PHP_INI_SYSTEM directive and can't be set in using ini_set(), .htaccess or user php.ini which rules out almost all shared hosting enviroments.
But interestingly, this is possible in WebFaction where I could set browscap in a user php.ini file which was parsed.

PHP
<?php
$imgCSS = "img";
$browser = get_browser(null, true);
if (($browser['browser'] = "Chrome" && $browser['version'] >= 9) || ($browser['browser'] = "Opera" && $browser['version'] >= 11.10))
$imgCSS = "webp";
?>
.
.
.
<link rel="stylesheet" type="text/css" media="all" href="<?php echo $imgCSS ?>.css" />
PHP 5.2

If you are getting something like ...

<b>Warning</b>:  get_browser() [<a href='function.get-browser'>function.get-browser</a>]: browscap ini directive not set in <b>/path/script.php</b> on line <b>7</b>

and if there is no way to set browscap, then you need to find an alternative browser detection like phpbrowscap.

I benchmarked this on a graphically heavy wordpress site, having 11 photographs in a slider on the homepage which takes a megabyte alone.

BrowserRequestsSizeTime
FireFox 3.6311.9 MB21.48s (onload: 20.62s)
Chrome 1132577.90KB6.51s (onload: 6.51s, DOMContentLoaded: 2.88s)

(I could not find the option to view total bytes downloaded in Opera dragonfly's network tab)

Side Note : When uploading webp images to google storage, S3 or any other cloud service, specify the content-type / mime-type.

gsutil -h "Cache-Control:public,max-age=31536000" -h "Content-Type: image/webp" cp -a public-read kitten.webp gs://[bucket]/images/kitten.webp
s3cmd put kitten.webp s3://[bucket]/images/ --acl-public --mime-type "image/webp" --add-header="Cache-Control:max-age=315360000"
Vanakkam !

0 comments: