2

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.

Output: Output Image. What I want: Expected output

import io, requests
from PIL import Image

user = Image.open(io.BytesIO(requests.get('https://cdn.discordapp.com/attachments/710929396013334608/720738818667446282/65578836_2994649093913191_1181627229703939865_n.jpg').content)).resize((40, 40))
back = Image.new('RGB', (646, 85), (54, 57, 63))
byteImg = io.BytesIO()
back.save(byteImg, format='PNG', quality=95)
back = Image.open(io.BytesIO(byteImg.getvalue()))
back.paste(user, (15, 23))

back.save('done.png') # Should save to the current directory
Ecks Dee
  • 455
  • 1
  • 6
  • 15
  • Have a look here... https://stackoverflow.com/q/60382952/2836621 – Mark Setchell Apr 03 '20 at 15:32
  • You need to create a mask with rounded-corners and pass it as the `mask=` argument to the `paste()`](https://pillow.readthedocs.io/en/latest/reference/Image.html#PIL.Image.Image.paste) method. You can use the `PIL.ImageDraw` module to draw the mask image (i.e. via its `ImageDraw.pieslice()` function). – martineau Apr 03 '20 at 15:37

1 Answers1

3

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.

from PIL import Image, ImageDraw, ImageFilter
import matplotlib.pyplot as plt

ims = Image.open('./lena_square.jpg')

blur_radius = 0
offset = 4
back_color = Image.new(ims.mode, ims.size, (0,0,0))
offset = blur_radius * 2 + offset
mask = Image.new("L", ims.size, 0)
draw = ImageDraw.Draw(mask)
draw.ellipse((offset, offset, ims.size[0] - offset, ims.size[1] - offset), fill=255)
mask = mask.filter(ImageFilter.GaussianBlur(blur_radius))

ims_round = Image.composite(ims, back_color, mask)
plt.imshow(ims_round)
ims_round.save('./lena_mask.jpg', quality=95)

enter image description here enter image description here

martineau
  • 119,623
  • 25
  • 170
  • 301
r-beginners
  • 31,170
  • 3
  • 14
  • 32