Skip to content

Add script for converting webp to jpeg or gif #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ Crop an image on specific coordinates

## webp

```md
webp.py
```

webp to jpg or gif converter

*Notice: This requires [Pillow](https://python-pillow.org/).*
Expand Down
34 changes: 34 additions & 0 deletions webp.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import os
from PIL import Image

# taken from https://stackoverflow.com/a/61242086
def isAnimated(file_path: str) -> bool:
with open(file_path, mode='rb') as file_handler:
file_handler.seek(12)
if file_handler.read(4) == b'VP8X':
file_handler.seek(20)
is_animated_byte = file_handler.read(1)
return (ord(is_animated_byte) >> 1) & 1
return False

def isTransparent(img: Image) -> bool:
return img.mode == "RGBA" or "transparency" in img.info

def convert(file_path: str, format = 'jpeg', overwrite = False, **params) -> None:
new_file_path = file_path[:-4] + format
img = Image.open(file_path)

# JPEG does not support alpha channel
if isTransparent(img) and format == 'jpeg':
img = img.convert('RGB')

img.save(new_file_path, format, **params)

if overwrite:
os.remove(file_path)

file_path = ''
if isAnimated(file_path):
convert(file_path, 'gif', quality=95, optimize=True, save_all=True)
else:
convert(file_path, 'jpeg', quality=95, optimize=True, subsampling=0)