Skip to content

Instantly share code, notes, and snippets.

@homm
Created March 23, 2013 16:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save homm/5228226 to your computer and use it in GitHub Desktop.
Save homm/5228226 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
from PIL import Image, ImageMath
def paste_composite(original, paste):
"""
Вставляет в первое изображение второе, с учетом альфаканала обоих.
Оба изображения должны быть в формате RGBA.
"""
# im._new(im.getdata(3)) быстрее split()[-1].
image_alpha = paste._new(paste.getdata(3))
# alpha_chanel — альфаканал результирующего изображения. Будет вставлен
# без зименений. im._new(im.getdata(3)) быстрее split()[-1].
alpha_chanel = original._new(original.getdata(3))
alpha_chanel.paste(Image.new('L', alpha_chanel.size, 255), image_alpha)
# blending_chanel — альфаканал, который будет использован для смешивания
# пикселей.
blending_chanel = ImageMath.eval("convert(a * 255 / b, 'L')",
a=image_alpha, b=alpha_chanel)
del image_alpha
original.paste(paste, (0, 0), blending_chanel)
del blending_chanel
original.putalpha(alpha_chanel)
del alpha_chanel
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment