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

Question:

I tried to export Alpha Channels of a All Images in The same Directory so I’ve used "os" to list all files in the directory, and an old img lib that is not working (PyCharm says Cannot find reference ‘split’ in ‘Image.pyi’)

And I think that Pillow doesn’t have the ability to separate the Alpha Channel…

I used this 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
Asked By: Shadow Company

||

Answers:

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

Answered By: Pedro Rocha
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.