I’ve pasted an image on a background, but I’m currently facing a problem where I don’t know how to round the corners of the pasted image. I want to round the image that is kept in the user variable from the script below.
JavaScript
x
12
12
1
import io, requests
2
from PIL import Image
3
4
user = Image.open(io.BytesIO(requests.get('https://cdn.discordapp.com/attachments/710929396013334608/720738818667446282/65578836_2994649093913191_1181627229703939865_n.jpg').content)).resize((40, 40))
5
back = Image.new('RGB', (646, 85), (54, 57, 63))
6
byteImg = io.BytesIO()
7
back.save(byteImg, format='PNG', quality=95)
8
back = Image.open(io.BytesIO(byteImg.getvalue()))
9
back.paste(user, (15, 23))
10
11
back.save('done.png') # Should save to the current directory
12
Advertisement
Answer
I learned how to compose images. We were able to create and compose a mask image. Image.composite
from the PIL
library. I used the article Composite two images according to a mask image with Python, Pillow as a reference.
JavaScript
1
18
18
1
from PIL import Image, ImageDraw, ImageFilter
2
import matplotlib.pyplot as plt
3
4
ims = Image.open('./lena_square.jpg')
5
6
blur_radius = 0
7
offset = 4
8
back_color = Image.new(ims.mode, ims.size, (0,0,0))
9
offset = blur_radius * 2 + offset
10
mask = Image.new("L", ims.size, 0)
11
draw = ImageDraw.Draw(mask)
12
draw.ellipse((offset, offset, ims.size[0] - offset, ims.size[1] - offset), fill=255)
13
mask = mask.filter(ImageFilter.GaussianBlur(blur_radius))
14
15
ims_round = Image.composite(ims, back_color, mask)
16
plt.imshow(ims_round)
17
ims_round.save('./lena_mask.jpg', quality=95)
18