Python PIL - the background appears opaque, not transparent

I want to create 32x32 thumbnails from uploaded images (actually avatars).

So that the thumbnail is not smaller than this size, I want to create a 32x32 transparent background and insert a thumbnail on it.

The code below is trying to do this. However, the avatar is displayed on a black and opaque background; I am losing transparency information somewhere through the process. Where am I doing wrong?

def handle_image(img):
    size = SMALL_AVATAR_IMAGE_SIZE
    img.thumbnail(size, Image.ANTIALIAS)  
    img = img.convert('RGBA')
    background = Image.new('RGBA', size, (255, 255, 255, 0))
    background.paste(img, (0, (size[1] - img.size[1]) / 2), img)
    img = background
    processed_image_small = ContentFile(img.tostring('jpeg', img.mode))
    targetpath = str(self.user.id) + '_S' + '.jpg'
    self.img_small.save(targetpath, processed_image_small,save=False)
+3
source share
2 answers

This is because JPEG cannot save the transparency information contained in the RGBA image. You can save the avatar in PNG format, which can save this information.

+5

JPG. JPEG . PNG- .

+5

Source: https://habr.com/ru/post/1718648/


All Articles