From 2b1bcbb058ed58aa2fe2c396ec98d8a9727fc783 Mon Sep 17 00:00:00 2001 From: The-Last-Cookie <50201659+The-Last-Cookie@users.noreply.github.com> Date: Thu, 15 Jun 2023 22:28:15 +0200 Subject: [PATCH 1/3] Add basic script to convert webp to jpeg or gif --- webp.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 webp.py diff --git a/webp.py b/webp.py new file mode 100644 index 0000000..f8d38d1 --- /dev/null +++ b/webp.py @@ -0,0 +1,26 @@ +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 convert(file_path: str, format = 'jpeg', overwrite = False, **params) -> None: + new_file_path = file_path[:-4] + format + img = Image.open(file_path) + img.save(new_file_path, format, **params) + + if overwrite: + os.remove(file_path) + +file_path = 'img.webp' +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) From 2eee80e9944e37bbf31af2d4e29f1ccb5612614d Mon Sep 17 00:00:00 2001 From: The-Last-Cookie <50201659+The-Last-Cookie@users.noreply.github.com> Date: Mon, 23 Sep 2024 00:36:56 +0200 Subject: [PATCH 2/3] Add support for transparency --- webp.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/webp.py b/webp.py index f8d38d1..21537f4 100644 --- a/webp.py +++ b/webp.py @@ -11,15 +11,23 @@ def isAnimated(file_path: str) -> bool: 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 = 'img.webp' +file_path = '' if isAnimated(file_path): convert(file_path, 'gif', quality=95, optimize=True, save_all=True) else: From fb9a34d9e8c04fb7bcb8599df85e3cd445f0e6f6 Mon Sep 17 00:00:00 2001 From: The-Last-Cookie <50201659+The-Last-Cookie@users.noreply.github.com> Date: Mon, 23 Sep 2024 14:18:23 +0200 Subject: [PATCH 3/3] Add filename to README --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 9ecfc15..52b1c3b 100644 --- a/README.md +++ b/README.md @@ -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/).*