
A long time ago, I had created a script where I could just enter a folder, run a command, and even with multiple files, it would convert WEBP images to JPG.
However, besides occasionally witnessing conversion failures, there was a time I had a folder with many .webp files and noticed a slight slowness.
So, I decided to rewrite the code in C++.
First of all, you need to have ImageMagick Dev (the .h API) installed on your machine. To do this, run:
Example for systems with APT:
sudo apt install imagemagick graphicsmagick-libmagick-dev-compatNow create the C++ file, for example: main.cpp and paste this code inside.
The code itself is self-explanatory; it lists the
.webpfiles, converts them to.jpg, and after that, removes the.webpfiles. If there are no.webpfiles in the directory where you run the binary, it issues a warning.
#include <Magick++.h>
#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;
int main(int argc, char **argv){
(void)argc;
Magick::InitializeMagick(*argv);
bool found = false;
for(const auto &entry : fs::directory_iterator(fs::current_path())){
if(entry.is_regular_file() && entry.path().extension() == ".webp"){
found = true;
std::string input = entry.path().string();
fs::path out_path = entry.path();
out_path.replace_extension(".jpg");
std::string output = out_path.string();
try{
Magick::Image img(input);
img.write(output);
fs::remove(entry.path());
}catch(Magick::Exception &e){
std::cerr << input << ": " << e.what() << "\n";
return EXIT_FAILURE;
}
}
}
if(!found){
std::cout << "There are no images to convert.\n";
}
}Compile with -ffast-math for even faster binary execution:
g++ -ffast-math -o w2j $(Magick++-config --cxxflags --cppflags) main.cpp $(Magick++-config --ldflags --libs)After that, just install it:
sudo install -v w2j /usr/local/bin/Then just use it, for example:
cd folder/with/many/webp/
w2jAnd all WEBP files will be converted to JPG and automatically deleted at the end.
Just out of curiosity, the GNU Bash script that did this was this:
w2jpg(){
shopt -s nullglob
local files=( *.webp )
(( ${#files[@]} == 0 )) && {
echo "No images to convert."
return
}
for f in "${files[@]}"; do
convert "$f" "${f%.webp}.jpg"
done
rm -- *.webp
}