Skip to content

Instantly share code, notes, and snippets.

@flxai
Created January 26, 2025 23:30
Show Gist options
  • Save flxai/ec469fa78d314386e9dcd9eef6f945c4 to your computer and use it in GitHub Desktop.
Save flxai/ec469fa78d314386e9dcd9eef6f945c4 to your computer and use it in GitHub Desktop.
Pandoc filter to convert all images to webp format
#!/usr/bin/env python
"""
Pandoc filter to convert all images to WebP format.
"""
import os
from pandocfilters import toJSONFilter, Image
from PIL import Image as PILImage
def convert_to_webp(image_path):
"""
Converts the given image to WebP format and returns the new file path.
"""
base, ext = os.path.splitext(image_path)
webp_path = f"{base}.webp"
try:
with PILImage.open(image_path) as img:
img.save(webp_path, format='webp')
return webp_path
except Exception as e:
print(f"Error converting {image_path} to WebP: {e}")
return image_path
def image_to_webp(key, value, format, meta):
if key == 'Image':
attrs, alt_text, [src, title] = value
webp_src = convert_to_webp(src)
return Image(attrs, alt_text, [webp_src, title])
if __name__ == "__main__":
toJSONFilter(image_to_webp)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment