笔者小白在实际过程中在将一张图片粘贴到另一张图片上的过程中,使用PIL先对图片进行旋转,但是发现旋转后像素是用黑色填充的。这并不是我想要的。于是接下来介绍一种方法在使用PIL旋转图片时,指定图像的填充的颜色。
当原始的图像没有alpha图层时,就可以使用alpha图层作为掩码将背景转换为白色。当旋转创建”背景”时,它使其完全透明。
#original image
img = Image.open('test.png')
#转换为有alpha层
im2 = img.convert('RGBA')
#旋转图像
rot = im2.rotate(22.2,expand = 1)
#与旋转图像大小相同的白色图像
fff = Image.new('RGBA',rot.size, 255,)* 4)
#使用alpha层的rot作为掩码创建一个复合图像
out = Image.composite(rot,fff,rot)
#保存你的工作回到mode ='1'或任何..)
out.convert(img.mode).save('test2.bmp')
在此基础上,如何应用旋转好的图片粘贴到另一张图像上呢。参考代码如下:
def add_cachet_img(img_url, angle, img_im, adress_x, adress_y, random_num):
cachet_img = Image.open(img_url)
cachet_img_a = cachet_img.convert('RGBA')
cachet_img_r = cachet_img_a.rotate(random.randrange((-1 * angle), angle))
cachet_img_f = Image.new('RGBA', cachet_img_r.size, (255, )*4)
cachet_img_new = Image.composite(cachet_img_r, cachet_img_f, cachet_img_r)
img_region = cachet_img_new.crop((0, 0, cachet_img.size[0], cachet_img.size[1]))
img_im.paste(img_region, (random.randint(adress_x, adress_x + random_num), random.randint(adress_y,adress_y + random_num)))
关于PIL复制和粘贴图片,可以参考笔者小白的另一篇blog。
参考文献:
1、http://www.it1352.com/532977.html 2018.4.28