Convert palettised images with transparency to RGB with white background

42 Views Asked by At

I'm trying to convert random images with transparency to RGB with white background:

def create_userpic():
    size = 320, 320
    output = BytesIO()
    image_filename = open((s.image_path + choice(listdir(s.image_path))), 'rb')
    image = Image.open(image_filename)
    new_image = Image.new('RGBA', image.size, 'white')
    new_image.paste(image, image)
    image = new_image.convert('RGB')
    image = image.resize(size)
    image.save(output, format='JPEG', quality=80)
    image.show()

This works perfectly on RGBA .png files, but fails on palettised ones with the 'ValueError: bad transparency mask' error.

I can convert palletized imaged to RGB using this method, but the results look really ugly:

def create_userpic():
    size = 320, 320
    output = BytesIO()
    image_filename = open((s.image_path + choice(listdir(s.image_path))), 'rb')
    image = Image.open(image_filename)
    image = image.convert('RGB')
    image = image.resize(size)
    image.save(output, format='JPEG', quality=80)
    image.show()

Conversion example:

enter image description here

How can I fix the transparency conversion issue?

0

There are 0 best solutions below