Skip to content

Commit

Permalink
add script to convert entire folder to webp
Browse files Browse the repository at this point in the history
  • Loading branch information
CarsonDavis committed Oct 13, 2024
1 parent cc60b95 commit b39ba22
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 3 deletions.
20 changes: 17 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,13 +130,27 @@ bundle install
Please see the [theme's docs](https://github.com/cotes2020/jekyll-theme-chirpy#documentation).

## Images

### Converting to WebP

I've been using the `cwebp` command to convert images to webp format. You can install it with homebrew.
```

```bash
brew install webp
```

This command converts a jpeg to a webp file at 70% compression.
This command converts a jpeg to a webp file at 70% compression:

```bash
cwebp -q 70 image_1.jpeg -o image_1.webp
```
cwebp -q 70 0010_S2Ark7u.jpeg -o 0010_S2Ark7u.webp

### Batch Converting an Entire Folder of Images to WebP

If you have a whole folder of images you want to convert to WebP format, you can use the `convert_to_webp.py` script. It will take all `.jpeg` and `.jpg` files in a folder, convert them to `.webp`, and place them in a new subfolder called `webp_images` inside the same folder.

To use the Python script, run the following command:

```bash
python convert_to_webp.py /path/to/your/images_folder
```
44 changes: 44 additions & 0 deletions convert_to_webp.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import os
import sys
import subprocess
from typing import NoReturn


def convert_images_to_webp(source_folder: str) -> None:
# Check if the source folder exists
if not os.path.exists(source_folder):
print(f"The folder {source_folder} does not exist.")
return

# Create a new folder inside the source folder for the WebP files
destination_folder: str = os.path.join(source_folder, "webp_images")
if not os.path.exists(destination_folder):
os.makedirs(destination_folder)

# Loop through each file in the source folder
for filename in os.listdir(source_folder):
if filename.lower().endswith(
(".jpeg", ".jpg")
): # Add more extensions if needed
source_path: str = os.path.join(source_folder, filename)
destination_path: str = os.path.join(
destination_folder, f"{os.path.splitext(filename)[0]}.webp"
)

# Run the cwebp command
subprocess.run(["cwebp", "-q", "70", source_path, "-o", destination_path])

print(f"Converted {filename} to {destination_path}")


def main() -> NoReturn:
if len(sys.argv) != 2:
print("Usage: python convert_to_webp.py <folder_path>")
sys.exit(1)

folder_path: str = sys.argv[1]
convert_images_to_webp(folder_path)


if __name__ == "__main__":
main()

0 comments on commit b39ba22

Please sign in to comment.