This blog is intended to show how we introduce google backed real-time image compression format webp to reduce image load time on client-side with zero downtime?
We have an application having numerous poster images of different resolution, so on a slow internet connection, rendering of these images on mobile devices was taking lots of time which is always frustrating for end-users, also it was causing an increase in load time for large size images of higher resolution.
So to tackle this problem we decided to compress images without compromising with quality. We were using ImageMagick with carrierwave for all the image processing and remote file upload. So we decided to compress the image using ImageMagick libraries to reduce the file size but it compresses the image at the cost of image quality. So no way this can be the solution. What’s now…?
The only port in the storm was webp– format developed by Google — which uses both lossy and lossless compression
Considering we already have ImageMagick installed on our system.
We have to install libwebp, a library used to add WebP encoding and decoding to your programs. Before that
Download dependency for libwebp.
sudo apt-get install libjpeg-dev libpng-dev libtiff-dev libgif-dev
Download latest libwebp and extract it.
wget http://downloads.webmproject.org/releases/webp/libwebp-0.4.3.tar.gz tar xf libwebp-0.4.3.tar.gz
Run the following commands to install libwebp.
cd libwebp-0.4.3/ ./configure make sudo make install
Run it on the console to confirm successful installation.
2.0.0p0 :002 > WebP.decoder_version => "0.4.3" 2.0.0p0 :003 > WebP.encoder_version => "0.4.3"
Now we need to add carrierwave-webp gem which is Ruby wrapper for libwebp.
Now that we have all of our prerequisites out of the way, we are now ready to convert our image to WebP.
Customize Carrierwave uploader to generate images in webp format.
class MediaUploader < CarrierWave::Uploader::Base include CarrierWave::MiniMagick include CarrierWave::WebP::Converter version :jpeg do process resize_to_fit: [720, 450] process convert: :jpeg end version :webp do process :convert_to_webp end end
So this way we have generated two different versions of images, one in jpg with given resolution (for fallback) and other in webp format.
Format Specific remote image URL
def return_url(poster, format) if poster.image.send(format).exists? url = poster.image.send(format).url else poster.image.jpeg.url //JPEG as fallback option. end end
- Not supported in iOS and Safari client.
- More effective for substantially large files.