Convert Images to WebP
Stop relying on sketchy, ad-filled websites. You can build your own tool to convert PNG and JPG images to WebP from anywhere. Historically, building such a tool yourself was often too time-consuming to justify. But now, with Gemini CLI, you can create a robust solution in less time than it takes to find an online converter. Even better, the workflow demonstrated here can be applied to generate all sorts of tools.
Step 1: Install Gemini CLI
I will assume that you have node already installed. Open a terminal, and run:
You can now start Gemini CLI and signin using your Google account. You get generous free usage ( reference).
Step 2: Building
This is the most critical step: providing Gemini with the necessary context to execute the task exactly as intended. Be as precise as possible and rely on your expertise to guide Gemini toward a viable solution. For instance, for this image-to-WebP tool, I know Python or Node.js are excellent choices due to their rich ecosystem of libraries, whereas other runtimes might lack the specific tools we need. Don't let Gemini guess what you already know.
A powerful trick I use is to explicitly ask Gemini for clarifying questions before it formulates a plan. This ensures nothing is overlooked. Here is the exact phrase I append to my initial prompts:
Please start by asking clarifying questions then come up with a clear detailed plan that I will review before you can start any implementation. finally please save the detailed plan to a text file for reference.
Currently, if you jump too quickly to the execution phase, Gemini will attempt to fill in missing context with reasonable assumptions. Details we typically discover during coding or architecture—such as file naming conventions, argument support, or output locations—are often missed at the start. Addressing these early is key to superior results.
By prompting Gemini to ask clarifying questions, we minimize the risk of omitting crucial details required to meet our expectations.
This is the full initial user prompt I used for this project:
These were the clarifying questions:
To ensure the script meets your needs, I have a few clarifying questions:
- Input: Do you want to pass a single file, multiple files, or a directory path? If a directory, should it search recursively?
- Output Location: Should the converted images be saved in the same folder as the original, or in a specific output folder?
- Naming: How should the new files be named (e.g., 'image.png' -> 'image.webp')?
- Quality: "Optimized for web" usually implies a balance between quality and size. Do you have a specific quality percentage in mind (e.g., 80%), or should I use a sensible default?
- Handling Existing Files: What should happen if the destination file already exists (overwrite, skip, or rename)?
- Installation: To run it "from anywhere," do you prefer using 'npm link' to make it a global command, or simply adding a shell alias/script wrapper yourself?
Once you answer these, I will create a detailed plan and save it to a file for your review.
I provided the following answers:
It then generated the following execution plan based on my initial prompt and my clarifying answers:
Plan: Image to WebP Converter
Objective
Create a Node.js script to convert PNG, JPG, and JPEG images to WebP format, optimized for web usage, maintaining aspect ratio. The script should work on single files or entire directories and be easily callable from anywhere.
Features
1. Input Handling
- If a file path is provided as an argument, convert only that file.
- If no argument is provided, convert all supported images in the current working directory.
2. Supported Formats:
- .png, .jpg, .jpeg (case-insensitive)
3. Output
- Save in the same directory as the source.
- Filename structure: '<original_name>.webp'.
- Overwrite existing files if they exist.
4. Optimization
- Target "Web Optimized" quality (defaulting to 80% quality which offers a good balance of size vs visual fidelity).
- Strictly maintain original aspect ratio (no resizing, just format conversion).
5. Global Usage:
- Designed to be used via a shell alias.
Implementation Steps
1. Project Initialization
- Initialize a Node.js project ('npm init -y').
- Set 'type: module' in 'package.json' to use ES modules.
2. Dependencies
- sharp: High-performance image processing library.
3. Script Logic ('convert.js')
-
Shebang: Add '#!/usr/bin/env node' at the top.
-
Argument Parsing: Check 'process.argv' for input path.
-
File Discovery:
- If arg provided: Verify it's a file.
- If no arg: Use 'fs.readdir' to find all matching files in 'process.cwd()'.
-
Conversion Function:
- Input: File path.
- Process: 'sharp(input).webp({ quality: 80 }).toFile(output)'.
- Output path derivation: Replace extension with '.webp'.
-
Feedback: Log "Converting: [file] -> [new_file]" and success/error status.
4. Verification & Testing
- Create a 'test' folder with sample images.
- Run the script with specific file argument.
- Run the script with no arguments.
- Verify output file existence, format, and aspect ratio preservation.
- Run 'npm run lint' and 'npm run build' (if applicable) to ensure quality.
5. Documentation ('README.md')
- Installation steps.
- Shell Alias Setup: Clear instructions on how to add the alias to '.bashrc', '.zshrc', etc.
- Example: 'alias towebp="node $(pwd)/convert.js"'
Review
Please review this plan. If approved, I will proceed with implementation.
If the plan isn't perfect, ask Gemini to modify it. In my case, the plan was spot on. Comparing the detailed plan to our initial brief request reveals just how many assumptions we were making. The key is really to get to that level of detail before starting the execution.
It appears the implementation of the Image to WebP Converter plan is complete and verified:
- Implemented convert.js with the requested specs (quality 80, aspect ratio preservation).
- Created the README.md with alias instructions.
- Verified the functionality with a test image.
Step 3: Install towebp
To make the towebp tool available from anywhere I can follow the instructions written for me in README.md. More specifically, I added the following to my ~/.bashrc (or ~/.zshrc).
where /path/to/convert-to-webp is the absolute path where convert.js is located on my computer
From the terminal, we can now do:
to convert a single file and:
to convert all files in the current directory.
Conclusion
When using tools like Gemini CLI, context is everything.However, instead of trying to provide all that context upfront, start with a solid foundation and iterate through clarifying questions until you have a comprehensive plan. Save that plan to a text file so that you can reference it later if needed.
I hope this guide was helpful. If you want to grab towebp (or see the code generated), check out the repository below.
