Any way to insert a round photo in reportlab?

This code crops the photo and saves it.

from PIL import Image, ImageDraw
import os

def prepare_mask(size, antialias = 2):
    mask = Image.new('L', (size[0] * antialias, size[1] * antialias), 0)
    ImageDraw.Draw(mask).ellipse((0, 0) + mask.size, fill=255)
    return mask.resize(size, Image.ANTIALIAS)

def crop(im, s):
    w, h = im.size
    k = w / s[0] - h / s[1]
    if k > 0: im = im.crop(((w - h) / 2, 0, (w + h) / 2, h))
    elif k < 0: im = im.crop((0, (h - w) / 2, w, (h + w) / 2))
    return im.resize(s, Image.ANTIALIAS)

size = (200, 200)

def do_crop(img):
    im = Image.open(img)
    im = crop(im, size)
    im.putalpha(prepare_mask(size, 4))
    output = str(img).replace('jpg', 'png')
    try:
        os.remove(img)
    except:
        print(f"[INFO] Error deleting photo [{img}]")
    else:
        print(f'[INFO] Photo deleted successfully [{img}]')

    try:
        im.save(output)
        print(f"[INFO] Photo saved successfully [{output}]")
    except:
        print(f"[INFO] Error saving photo [{output}]")

Next, somewhere in the code in another file, I try to view this photo in PDF.

self.can.drawImage(f'user_images\{self.user_id}user_photo.png', 300, 500, 200, 200)

#self.can - Canvas OBJECT

After that, unfortunately, when I save everything in the original PDF file, this photo is not round, but becomes square, frames are added, what can I do about it?

Answer

I am writing this for people with a similar problem, everything is simple, inserting a round photo, it had a “transparent” background, I will not fully explain how it works, but here’s what you need to do to make the reportlab understand what you want.

Previous version.

self.can.drawImage(f'user_images\{self.user_id}user_photo.png', 300, 500, 200, 200)

New version

self.can.drawImage(f'user_images\{self.user_id}user_photo.png', 300, 500, 200, 200, mask='auto')

Added argument mask = 'auto'