Optimizing images for web use is essential for faster loading times and better performance. In this guide, we’ll show you how to create a Python script to optimize PNG and WebP images, and even convert it into an executable file for ease of use.
Prerequisites
- Python installed on your machine (version 3.6 or above).
- Basic knowledge of Python and the command line.
- Install the required library using:
pip install pillow
PowerShellThe Python Script
Below is the complete Python script to optimize images:
import os
from PIL import Image
def optimize_images():
# Define folders
current_folder = os.getcwd()
optimized_folder = os.path.join(current_folder, "optimized")
# Ensure the output folder exists
if not os.path.exists(optimized_folder):
os.makedirs(optimized_folder)
# Supported formats
supported_formats = (".png", ".webp")
# Iterate through files in the current folder
for filename in os.listdir(current_folder):
if filename.lower().endswith(supported_formats):
input_path = os.path.join(current_folder, filename)
output_path = os.path.join(optimized_folder, filename)
# Skip already optimized images
if os.path.exists(output_path):
print(f"Skipping already optimized image: {filename}")
continue
try:
# Open the image
with Image.open(input_path) as img:
if filename.lower().endswith(".png"):
# Optimize PNG
img.save(output_path, format="PNG", optimize=True)
elif filename.lower().endswith(".webp"):
# Optimize WebP with maximum compression settings
img.save(output_path, format="WEBP", quality=75, method=6)
print(f"Optimized: {filename}")
except Exception as e:
print(f"Failed to optimize {filename}: {e}")
if __name__ == "__main__":
optimize_images()
PythonExplanation
- Supported Formats: The script works with
.png
and.webp
files. - Optimized Folder: All optimized files are saved in a subfolder named
optimized
. - Skipping Optimized Images: The script skips images that already exist in the
optimized
folder. - Compression Settings: For PNGs, it uses Pillow’s
optimize=True
, and for WebP, it appliesquality=75
withmethod=6
for maximum compression.
Creating an Executable
You can convert this script into an executable file for ease of use.
Install PyInstaller:
pip install pyinstaller
PowerShellCreate Executable:
pyinstaller --onefile image_optimizer.py
PowerShellLocate Executable:
- The executable will be in the
dist
folder asimage_optimizer.exe
.
Test the Executable: Place the .exe
file into a directory with images to optimize. Double-click or run it via the command line to start the optimization process.
Conclusion
This script provides an efficient solution for optimizing images for the web, ensuring fast performance. Converting it into an executable enhances usability, even for non-technical users. Start optimizing today!
README.mc
# Image Optimizer
This script optimizes PNG and WebP images for web use, reducing their size without compromising quality.
## Features
- Supports PNG and WebP formats.
- Saves optimized images in a separate folder.
- Skips already optimized files.
## How to Use
1. Place images in the same directory as the script.
2. Run the script:
```bash
python image_optimizer.py
XMLRequirements
- Python 3.6+
- Pillow library
Install dependencies:
pip install pillow
pip install pyinstaller
PowerShell