Created
July 18, 2023 18:36
-
-
Save nitori/116909f1db4917da59175fd4ea0a6c1e to your computer and use it in GitHub Desktop.
convert image to provided palette
This file contains hidden or 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
| from itertools import chain | |
| import sys | |
| from PIL import Image | |
| # Connler's Cool Content Canvas | |
| COLORS = { | |
| 0: (0, 0, 0), # 000000 | |
| 1: (34, 34, 34), # 222222 | |
| 2: (85, 85, 85), # 555555 | |
| 3: (136, 136, 136), # 888888 | |
| 4: (205, 205, 205), # cdcdcd | |
| 5: (255, 255, 255), # ffffff | |
| 6: (255, 213, 188), # ffd5bc | |
| 7: (255, 183, 131), # ffb783 | |
| 8: (182, 109, 61), # b66d3d | |
| 9: (119, 67, 31), # 77431f | |
| 10: (252, 117, 16), # fc7510 | |
| 11: (252, 168, 14), # fca80e | |
| 12: (253, 232, 23), # fde817 | |
| 13: (255, 244, 145), # fff491 | |
| 14: (190, 255, 64), # beff40 | |
| 15: (112, 221, 19), # 70dd13 | |
| 16: (49, 161, 23), # 31a117 | |
| 17: (11, 95, 53), # 0b5f35 | |
| 18: (39, 126, 108), # 277e6c | |
| 19: (50, 182, 159), # 32b69f | |
| 20: (136, 255, 243), # 88fff3 | |
| 21: (36, 181, 254), # 24b5fe | |
| 22: (18, 92, 199), # 125cc7 | |
| 23: (202, 183, 205), # cab7cd | |
| 24: (38, 41, 96), # 262960 | |
| 25: (139, 47, 168), # 8b2fa8 | |
| 26: (210, 76, 233), # d24ce9 | |
| 27: (255, 89, 239), # ff59ef | |
| 28: (255, 169, 217), # ffa9d9 | |
| 29: (255, 100, 116), # ff6474 | |
| 30: (240, 37, 35), # f02523 | |
| 31: (177, 18, 6), # b11206 | |
| 32: (116, 12, 0), # 740c00 | |
| } | |
| def get_palette(): | |
| palette = chain.from_iterable(COLORS.values()) | |
| palette = list(palette) | |
| p_img = Image.new('P', (16, 16)) | |
| p_img.putpalette(palette) | |
| return p_img | |
| def conv_palette(im: Image) -> Image: | |
| *_, alpha = im.split() | |
| bg = Image.new('RGBA', im.size, (255, 255, 255, 255)) | |
| bg.alpha_composite(im) | |
| im = bg.convert('RGB') | |
| p_img = get_palette() | |
| # im = im.quantize(256).convert('RGB') # sometimes improves result | |
| im = im.quantize(palette=p_img, dither=0) | |
| return im, alpha | |
| def main(): | |
| im = Image.open(sys.argv[1]).convert('RGBA') | |
| im, alpha = conv_palette(im) | |
| im = im.convert('RGBA') | |
| im.putalpha(alpha) | |
| im.save(sys.argv[2]) | |
| if __name__ == '__main__': | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment