Skip to content

Instantly share code, notes, and snippets.

@ahadyekta
Created January 27, 2018 09:51
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save ahadyekta/8803818246f0aefe3a6a3a989a3a7804 to your computer and use it in GitHub Desktop.
Save ahadyekta/8803818246f0aefe3a6a3a989a3a7804 to your computer and use it in GitHub Desktop.
Batch convert JPG to WebP in Ubuntu
#First install the webp converter by this
sudo apt-get install webp
#go inside the directory where all images are there
#make sure all images are in RGB color mode, otherwise you will get error for CMYK images.
#Convert all images to RGB by this command (you should install ImageMagik to do that)
for f in *.jpg; do convert -colorspace RGB "$f" "${f}"; done
#finally convert all images to Webp format
for f in *.jpg; do cwebp -q 90 "$f" -o "${f}".webp; done
#Now you have filename.jpg.webp beside filename.jpg for all your images.
#You can set the nginx or other webservers to conditionally show webp instead of jpg if browser support
#Read this page to setup it in nginx config : https://github.com/uhop/grunt-tight-sprite/wiki/Recipe:-serve-WebP-with-nginx-conditionally
@yoursantu
Copy link

yoursantu commented Jan 29, 2020

Hi,
I have checked the command:
for f in *.jpg; do cwebp -q 90 "$f" -o "${f}".webp; done
this will convert all jpg files within the folder but
command returns *.jpg.webp instead of *.webp!!

what is the solution!?

@motoroller95
Copy link

motoroller95 commented Oct 8, 2020

for i in find apps -type f \( -iname "*.jpg" -o -iname "*.png" \); do cwebp -q 90 "$i" -o "${i%%.*}".webp; done

@sumonst21
Copy link

sumonst21 commented Dec 22, 2020

@yoursantu

find ./ -type f -name '*.png' | xargs -P 8 -I {} sh -c 'cwebp -q 75 $1 -o "${1%.png}.webp"' _ {} \;

check this article for explained details

@Mijsoot
Copy link

Mijsoot commented Sep 2, 2021

for i in find apps -type f \( -iname "*.jpg" -o -iname "*.png" \); do cwebp -q 90 "$i" -o "${i%%.*}".webp; done

@motoroller95
Thank you for clarifying, but I had to put some backticks for command Line. And I added the filter on the files modified less than 24 hours ago (-ctime 0) like this :
for_find_cwebp_02_09_21

I had to make an image because backtick is not supported in this editor, but here is the line without backtick :
for i in find /directory -ctime 0 -type f ( -iname ".jpg" -o -iname ".png" ); do cwebp -q 90 "$i" -o "${i%%.*}"".webp"; done

and I think that a double quote was also missing !

instead of -ctime 0 you can use -mtime -1 which is maybe better !

@uiovn
Copy link

uiovn commented Mar 25, 2024

for f in *.jpg; do cwebp $f -o ${f%.jpg}.webp; done

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment