I'm pasting an cropped image to another image.
Paste the cropped image.
It pasted the original for some bizarre reason.
Edit: Minimized code.
import os
from PIL import Image, ImageDraw, ImageOps, ImageFont, ImageFilter
filename = "image to crop.png"
offset = 50,50
size = 400,400
avatar = Image.open(filename)
avatar = avatar.resize(size, Image.ANTIALIAS)
rad = 200
circle = Image.new('L', (rad * 2, rad * 2), 0)
draw = ImageDraw.Draw(circle)
draw.ellipse((0, 0, rad * 2, rad * 2), fill=255)
alpha = Image.new('L', _avatar.size, "white")
w, h = _avatar.size
alpha.paste(circle.crop((0, 0, rad, rad)), (0, 0))
alpha.paste(circle.crop((0, rad, rad, rad * 2)), (0, h - rad))
alpha.paste(circle.crop((rad, 0, rad * 2, rad)), (w - rad, 0))
alpha.paste(circle.crop((rad, rad, rad * 2, rad * 2)), (w - rad, h - rad))
alpha = alpha.resize(size)
avatar.putalpha(alpha)
background = Image.open("image to paste to.png")
background.paste(avatar, offset)
background.save("image with cropped image pasted.png")
Thank you for the code example.
Please could you reduce it down to say, 10 or so essential lines that still reproduces the problem?
I shortened it @hugovk, please check my edit.
Which of the five pastes has the problem?
The last one
Here's a small working example:
from PIL import Image
red = Image.new("RGB", (200, 200), "red")
blue = Image.new("RGB", (200, 200), "blue")
# red.show()
# blue.show()
cropped_red = red.crop((0, 0, 10, 10))
blue.paste(cropped_red, (20, 20))
blue.show()
It creates this image:

but the red isn't circle 馃
i meant to crop it as a circle
see, the file saved is cropped as a circle, but when i paste it, it pastes the original
from PIL import Image, ImageDraw, ImageOps
big_size = (200, 200)
small_size = (20, 20)
red = Image.new("RGBA", big_size, "red")
blue = Image.new("RGBA", big_size, "blue")
mask = Image.new("L", big_size, 0)
draw = ImageDraw.Draw(mask)
draw.ellipse((0, 0) + small_size, fill=255)
cropped_red = ImageOps.fit(red, mask.size, centering=(0.5, 0.5))
cropped_red.putalpha(mask)
# cropped_red.show()
blue.paste(cropped_red, small_size, mask)
blue.show()

oh thanks
OMG IT WORKED THANK YOU SO MUCH!
You're welcome!
epic

Nice!
@hugovk When i crop an transparent image it appears with a black background, how do i fix this?
@hugovk
Please share the code you're using, again please follow the "Minimal, Complete, and Verifiable" guidelines: https://stackoverflow.com/help/mcve
i haven't changed it at all
it's still the same
If anyone wondering what the answer had did, it's basically passing the mask into the paste() as well
This line:
blue.paste(cropped_red, small_size, mask)
If anyone wondering what the answer had did, it's basically passing the
maskinto thepaste()as wellThis line:
blue.paste(cropped_red, small_size, mask)
this is it, thank you so much!
Most helpful comment