TURN JPEGS AND PNGS INTO WEB PS
AI Overview
This Python code snippet uses the Pillow library to convert JPG and PNG images into WebP format.
Prerequisites
You need to install the Pillow library:
bash
pip install Pillow
Code Snippet: Convert Single Image
python
from PIL import Image
import os
def convert_to_webp(source_path, quality=80): """Converts a jpg/png image to webp"""
image = Image.open(source_path) # Convert RGBA to RGB if necessary (for PNGs with transparency)
if image.mode == 'RGBA': image = image.convert('RGB') output_path = os.path.splitext(source_path)[0] + ".webp"
image.save(output_path, "webp", quality=quality) print(f"Successfully converted {source_path} to {output_path}")
# Example usage:
# convert_to_webp("input.jpg")
# convert_to_webp("photo.png")
Code Snippet: Batch Convert Folder
This script will convert all JPEGs and PNGs in the specified folder.
python
from PIL import Image
import os
import glob
def batch_convert_to_webp(folder_path, quality=80): # Supported formats
types = ('/*.jpg', '/*.jpeg', '/*.png') image_files = [] # Get all files
for t in types: image_files.extend(glob.glob(folder_path + t)) for file in image_files: try: image = Image.open(file) # Ensure proper conversion for different modes
if image.mode == 'RGBA': image = image.convert('RGB') output_path = os.path.splitext(file)[0] + ".webp"
image.save(output_path, "webp", quality=quality) print(f"Converted: {os.path.basename(file)}") except Exception as e: print(f"Error converting {file}: {e}")
# Run:
# batch_convert_to_webp("./images")
Key Considerations
- Quality: The
qualityparameter (0–100) sets the WebP compression strength. A value of 80 is usually a good balance between quality and size. - Transparency: PNG files with transparency should ideally be saved with
.convert('RGBA')or handled specifically if lossy compression is required, but.convert('RGB')is generally safer for standard web usage. - Batching: The batch script creates new files without deleting the original one
FOR WORDPRESS SNIPPET
In WordPress, the best way to handle this is by hooking into the upload process using a PHP snippet. This ensures that every time you upload a JPEG or PNG to your Media Library, a WebP version is automatically generated.
Option 1: Custom Code (No Plugin)
You can add this snippet to your theme’s functions.php file or use a plugin like WPCode to manage it. This code uses the WordPress wp_handle_upload filter to detect new uploads and convert them using the server’s GD or Imagick library.
php
/** * Automatically convert uploaded JPEG/PNG images to WebP */
add_filter('wp_handle_upload', 'convert_to_webp_on_upload');
function convert_to_webp_on_upload($upload) { $file_path = $upload['file']; $file_type = $upload['type']; // Only target JPEG and PNG
if (!in_array($file_type, ['image/jpeg', 'image/png'])) { return $upload; } $editor = wp_get_image_editor($file_path); if (!is_wp_error($editor)) { $webp_path = str_replace(pathinfo($file_path, PATHINFO_EXTENSION), 'webp', $file_path); // Save the WebP version
$editor->save($webp_path, 'image/webp'); // OPTIONAL: Uncomment the line below to delete the original JPG/PNG after conversion
// unlink($file_path);
} return $upload;}
Use code with caution.
Note: If you delete the original file (using unlink), make sure your theme supports serving WebP to all browsers.
Option 2: Recommended Plugins
If you prefer a more robust solution that also handles existing images (bulk conversion), these plugins are highly rated:
- Converter for Media: Great for beginners. It converts your entire library with one click and serves WebP only to supported browsers.
- Imagify: Best if you also want smart compression to further reduce file sizes.
- WebP Express: A more technical option that offers multiple conversion methods like
cwebporvips
FINAL CODE SNIPPET
The Code Snippet
php
/** * Automatically convert new JPEG and PNG uploads to WebP. */
add_filter('wp_handle_upload', 'convert_to_webp_on_upload');
function convert_to_webp_on_upload($upload) { // Only target JPEG and PNG files
if ($upload['type'] == 'image/jpeg' || $upload['type'] == 'image/png') { $file_path = $upload['file']; // Check if the server has GD or Imagick extensions active
if (extension_loaded('imagick') || extension_loaded('gd')) { $image_editor = wp_get_image_editor($file_path); if (!is_wp_error($image_editor)) { $file_info = pathinfo($file_path); $dirname = $file_info['dirname']; $filename = $file_info['filename']; // Create the new WebP file path
$new_file_path = $dirname . '/' . $filename . '.webp'; // Save as WebP (quality set to 80)
$saved_image = $image_editor->save($new_file_path, 'image/webp'); // If successful, update the upload array to point to the new WebP file
if (!is_wp_error($saved_image) && file_exists($saved_image['path'])) { $upload['file'] = $saved_image['path']; $upload['url'] = str_replace(basename($upload['url']), basename($saved_image['path']), $upload['url']); $upload['type'] = 'image/webp'; // DELETE the original JPG/PNG to save space (optional)
@unlink($file_path); } } } } return $upload;}
How to Install via WP Code Snippets
- Go to Snippets > Add New in your WordPress dashboard.
- Give your snippet a title, like “Auto WebP Conversion on Upload.”
- Set the Code Type to PHP Snippet.
- Paste the code above into the editor.
- Set the Insertion Method to Auto Insert and Location to Run everywhere.
- Toggle the switch to Active and click Save Snippet
