Skip to content

Commit

Permalink
Update images.py
Browse files Browse the repository at this point in the history
The `flatten` function has been updated with a conditional check to see if the image has an "RGBA" mode, meaning it contains an alpha channel for transparency. If that is the case, it flattens the image by creating a new solid background image with the specified background color and pasting the original image onto it, using the original image itself as the mask to retain its alpha transparency. Finally, the function returns the modified image converted to "RGB" mode with no transparency.
  • Loading branch information
chiragn888 authored Feb 19, 2024
1 parent cf2772f commit 0d34e28
Showing 1 changed file with 17 additions and 8 deletions.
25 changes: 17 additions & 8 deletions modules/images.py
Original file line number Diff line number Diff line change
Expand Up @@ -783,11 +783,20 @@ def image_data(data):


def flatten(img, bgcolor):
"""replaces transparency with bgcolor (example: "#ffffff"), returning an RGB mode image with no transparency"""

if img.mode == "RGBA":
background = Image.new('RGBA', img.size, bgcolor)
background.paste(img, mask=img)
img = background

return img.convert('RGB')
if img.mode in ("RGB", "RGBA"):
with_alpha = "A" in img.getbands()

if with_alpha and isinstance(bgcolor, bytes):
alpha = img.split()[3]
bg = Image.new("RGB", img.size, bgcolor)
bg.paste(img, mask=alpha)
return bg
elif with_alpha and not isinstance(bgcolor, bytes):
background = Image.new('RGBA', img.size, bgcolor)
background.paste(img, mask=img)
img = background
return img.convert('RGB')
else:
return img

return img

0 comments on commit 0d34e28

Please sign in to comment.