@@ -50,18 +50,26 @@ def webp_blob(image: PIL.Image.Image) -> protos.Blob:
5050def 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