To get the alpha layer of an RGBA image all you need to do is:
red, green, blue, alpha = img.split()
or
alpha = img.split()[-1]
And there is a method to set the alpha layer:
img.putalpha(alpha)
The transparency key is only used to define the transparency index in the palette mode (P). If you want to cover the palette mode transparency case as well and cover all cases you could do this
if img.mode in ('RGBA', 'LA') or (img.mode == 'P' and 'transparency' in img.info):
alpha = img.convert('RGBA').split()[-1]
Note: The convert method is needed when the image.mode is LA, because of a bug in PIL.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…