PIL粘贴原始图像而不是裁剪的图像

时间:2018-11-25 20:15:05

标签: python-3.x python-imaging-library

我想获得一些帮助,为什么在保存图像时Pillow不能放裁好的图像而不是原始图像? 当我在裁切后保存它时,它显示为裁切,但是当我粘贴它时,即使保存裁切的图像并加载裁切的图像然后粘贴,它也会粘贴原始图像。 这是我的代码,重新创建问题:

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")

2 个答案:

答案 0 :(得分:0)

在444行上,您没有分配调整大小的输出。 resize返回一个新图像,它不会修改原始图像。

答案 1 :(得分:0)

所以我找到了解决方案!问题是粘贴时我没有分配遮罩! 这是修复它的代码:

mask = Image.new("L", size, 0)
draw = ImageDraw.Draw(mask)
draw.ellipse((0, 0) + size, fill=255)
avatar = ImageOps.fit(avatar, mask.size, centering=(0.5, 0.5))
avatar.putalpha(mask)
background = Image.open("welcomecardbackground.jpg")
background.paste(avatar, offset, mask)

代替

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)