From your initial description, the following idea seems equivalent. Let X, Y be two RGBA images. Combine X and Y by looking at the RGB stripes from X and the RGBA stripes from Y, creating an image of Z. Set the range A to Z relative to the strip A to X. This contradicts your final statement, but seems to give the expected output in this situation.
So this is the code:
image = '1.png' watermark = '2.png' wmark = Image.open(watermark) img = Image.open(image) ia, wa = None, None if len(img.getbands()) == 4: ir, ig, ib, ia = img.split() img = Image.merge('RGB', (ir, ig, ib)) if len(wmark.getbands()) == 4: wa = wmark.split()[-1] img.paste(wmark, (0, 0), wmark) if ia: if wa: # XXX This seems to solve the contradiction, discard if unwanted. ia = max_alpha(wa, ia) img.putalpha(ia) img.save('result.png')
where the max_alpha function is:
def max_alpha(a, b): # Assumption: 'a' and 'b' are of same size im_a = a.load() im_b = b.load() width, height = a.size alpha = Image.new('L', (width, height)) im = alpha.load() for x in xrange(width): for y in xrange(height): im[x, y] = max(im_a[x, y], im_b[x, y]) return alpha
This new feature seems to account for this contradiction.
source share