Stafini
BlogFlashcardsProjectsResume

Creating WebP Images with the Command Line

Pink Tulip & window light

When I'm writing post for my site, there were many times I need to optimize images to Webp format then upload them to Cloudinary. There are a lot of website providing image optimization into webp but after trying them they feel too sluggish and slow for my taste. Luckiky there are simple tool to run with your computer command line called cwebp

Let's get started by setting it up, for MacOS, windows user can check here: https://developers.google.com/speed/webp/docs/precompiled

brew install webp

After homebrew is done running, just navigate (with command line) to your disirable image folder, then with command line

cwebp -q 50 images/flower1.jpg -o images/flower1.webp

This command converts, at a quality of 50 (0 is the worst; 100 is the best), the images/flower1.jpg file and saves it as images/flower1.webp.

After doing this, you should see something like this in the console:

Saving file 'images/flower1.webp'
File:      images/flower1.jpg
Dimension: 504 x 378
Output:    29538 bytes Y-U-V-All-PSNR 34.57 36.57 36.12   35.09 dB
           (1.24 bpp)
block count:  intra4:        750  (97.66%)
              intra16:        18  (2.34%)
              skipped:         0  (0.00%)
bytes used:  header:            116  (0.4%)
             mode-partition:   4014  (13.6%)
 Residuals bytes  |segment 1|segment 2|segment 3|segment 4|  total
    macroblocks:  |      22%|      26%|      36%|      17%|     768
      quantizer:  |      52 |      42 |      33 |      24 |
   filter level:  |      16 |       9 |       6 |      26 |

You've just successfully converted the image to WebP.

However, running the cwebp command one image at a time like this would take a long time to convert many images. If you need to do this, you can use a script instead.

`for file in images/*; do cwebp -q 50 "$file" -o "${file%.*}.webp"; done`

This script converts, at a quality of 50, all the files in the images/ directory, and saves them as a new file (same filename, but with a .webp file extension) in the same directory.

Let's say you have 3 flower.jpg files in the folder you should now have 6 files in your images/ directory:

flower1.jpg
flower1.webp
flower2.jpg
flower2.webp
flower3.png
flower3.webp