Created
July 29, 2022 16:04
-
-
Save kezzyhko/1cd526a8b6811fb5cf8fa3e156383fef to your computer and use it in GitHub Desktop.
Change image transparency, but preserve color data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import argparse | |
import pathlib | |
from PIL import Image | |
def transparency_type(value, min=0, max=255): | |
try: | |
value = int(value) | |
if min <= value <= max: | |
return value | |
else: | |
raise argparse.ArgumentTypeError('value not in range %s-%s' % (min, max)) | |
except ValueError: | |
raise argparse.ArgumentTypeError("invalid int value: '%s'" % (value)) | |
description = ( "Change image transparency, but preserve color data. Examples:\n" | |
"\tpython change_transparency.py -i in.png -t 0 -o out.png\n" | |
"\tpython change_transparency.py -i out.png -t 255 -o restored.png\n") | |
parser = argparse.ArgumentParser(description=description, formatter_class=argparse.RawTextHelpFormatter, add_help=False) | |
required_args = parser.add_argument_group('Required arguments') | |
optional_args = parser.add_argument_group('Optional arguments') | |
optional_args.add_argument('--help', '-h', action='help', default=argparse.SUPPRESS, help='show this help message and exit') | |
required_args.add_argument('--input', '-i', type=pathlib.Path, help='path to input image', required=True) | |
required_args.add_argument('--transparency', '-t', type=transparency_type, metavar='0-255', help='target transparency (0-255)', required=True) | |
optional_args.add_argument('--output', '-o', type=pathlib.Path, help='path to output image') | |
args = parser.parse_args() | |
img = Image.open(args.input) | |
img = img.convert("RGBA") | |
items = img.getdata() | |
new_items = [] | |
for item in items: | |
new_items.append((item[0], item[1], item[2], args.transparency)) | |
img.putdata(new_items) | |
img.save(args.output or args.input, "PNG") | |
print("Successful") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Pillow==9.2.0 | |
pathlib==1.0.1 | |
argparse==1.4.0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment