pythonpython-3.xpngtga

How to extract Alpha Channel from a TGA or PNG image using Python?


I tried to export Alpha Channels of a All Images in The same Directory so I've used "os" to list all files in my case all images in the Directory and an old img lib which is not working or to be clear PyCharm says Cannot find reference 'split' in 'Image.pyi' and as I know Pillow or PLI doesn't have the ability to separate the Alpha Channel... if there is any mistake in the code or anything forgive me i'm a beginner. also I used this "https://stackoverflow.com/questions/1962795/how-to-get-alpha-value-of-a-png-image-with-pil" as help or a reference

import os
import img
from PIL import Image

# list all files
dirPath = input("Enter The Path Please: ")
dirList = os.listdir(dirPath)

# prints all files # just for debugging
print(dirList)

x = 0
for x in range(len(dirList)):
    if x == len(dirList) + 1:
        break
    dirList[x] = img.split()[-1]
    x += 1

Solution

  • Try with this...

    import os
    from PIL import Image
    
    dirPath = input("Enter The Path Please: ")
    
    for file in os.listdir(dirPath):
        try:
            img = Image.open(f"{dirPath}/{file}")
            r, g, b, a = img.split()
            a.save(f"{file.split('.')[0]}-alpha.png")
        except ValueError:
            print(f"Image {file} doesn't have Alpha channel")
    

    This code try to extract alpha channel from every img in the directory, if fails print that the image doesn't have alpha channel