Skip to content

Instantly share code, notes, and snippets.

@grangerp
Created April 12, 2018 17:39
Show Gist options
  • Save grangerp/7029b4cae42d4bbad8948a0a57b2faaf to your computer and use it in GitHub Desktop.
Save grangerp/7029b4cae42d4bbad8948a0a57b2faaf to your computer and use it in GitHub Desktop.
convert image white to transparency
from PIL import Image, ImageOps
def convert(src, dst, size=(224, 224)):
original = Image.open(src)
thumb = ImageOps.fit(original, size, Image.ANTIALIAS)
if thumb.mode == 'RGBA':
# convert transparency to white
thumb.load() # test
background = Image.new('RGB', thumb.size, (255, 255, 255))
background.paste(thumb, mask=thumb.split()[3])
thumb = background
# convert ot png with white as transparency
thumb = thumb.convert("RGBA")
datas = thumb.getdata()
newData = []
for item in datas:
if item[0] == 255 and item[1] == 255 and item[2] == 255:
newData.append((255, 255, 255, 0))
else:
newData.append(item)
thumb.putdata(newData)
thumb.save(dst, 'PNG')
if __name__ == '__main__':
convert('media/product/weetabix-crispy-minis-fruit-nut-292141.png', 'res.png')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment