Skip to content
This repository was archived by the owner on Dec 16, 2025. It is now read-only.

Commit a20e52b

Browse files
modified
1 parent 5f7ddd8 commit a20e52b

File tree

1 file changed

+12
-4
lines changed

1 file changed

+12
-4
lines changed

IMAGE_ENCODING_FIX.md

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -50,18 +50,26 @@ def webp_blob(image: PIL.Image.Image) -> protos.Blob:
5050
def webp_blob(image: PIL.Image.Image) -> protos.Blob:
5151
image_io = io.BytesIO()
5252

53-
# Convert RGBA images to RGB before saving as WebP
54-
if image.mode == "RGBA":
53+
# Convert RGBA images to RGB before saving as WebP to avoid compatibility issues
54+
# Some Pillow versions have issues with RGBA -> WebP lossless conversion
55+
if image.mode in ("RGBA", "LA"):
56+
# Create a white background
5557
rgb_image = PIL.Image.new("RGB", image.size, (255, 255, 255))
56-
rgb_image.paste(image, mask=image.split()[3])
58+
# Paste the image using its alpha channel as mask
59+
rgb_image.paste(image, mask=image.getchannel('A'))
5760
image = rgb_image
5861
elif image.mode not in ("RGB", "L"):
62+
# Convert other modes (e.g., P) to RGB.
63+
# Note: .convert('RGB') might use a black background for transparent 'P' images.
5964
image = image.convert("RGB")
6065

6166
try:
6267
image.save(image_io, format="webp", lossless=True)
6368
except Exception as e:
64-
# Fallback to PNG format
69+
import logging
70+
logging.warning(f"WebP conversion failed, falling back to PNG. Reason: {e}")
71+
# If lossless WebP fails, fall back to PNG format
72+
# PNG is widely supported and provides lossless compression
6573
image_io = io.BytesIO()
6674
image.save(image_io, format="png")
6775
image_io.seek(0)

0 commit comments

Comments
 (0)