Last active
September 29, 2023 15:14
-
-
Save JamesTheAwesomeDude/f640a61215b2ffc7129e6690fed60a0c to your computer and use it in GitHub Desktop.
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
from PIL import Image # https://packages.ubuntu.com/jammy/python3-pil https://pypi.org/project/Pillow/ | |
import cairosvg.surface # https://packages.ubuntu.com/jammy/python3-cairosvg https://pypi.org/project/CairoSVG/ | |
from io import BytesIO | |
def svg2ico(*args, resolutions={128, 96, 64, 48, 32, 16}, write_to=None, dpi=96, winxp_compat=False, **kwargs): | |
maxres = max(resolutions, key=lambda res: (0, res) if res is not None else (1, ), default=None) | |
# "DPI" from https://github.com/Kozea/CairoSVG/blob/2.2.0/cairosvg/__init__.py#L62 | |
imsave_kwargs = {'format': 'ICO'} | |
if winxp_compat: | |
# Needs at least Pillow 8.3.0 (released July 2021) | |
# https://github.com/python-pillow/Pillow/issues/2512 | |
imsave_kwargs['bitmap_format'] = 'bmp' | |
t = cairosvg.surface.Tree(*args, **kwargs) | |
imsave_kwargs['append_images'] = [] | |
for res in resolutions: | |
f = BytesIO() | |
cairosvg.surface.PNGSurface(t, f, dpi, | |
output_width=res, output_height=res).finish() | |
f.seek(0) | |
if res is maxres: | |
im_main = Image.open(f) | |
else: | |
imsave_kwargs['append_images'].append(Image.open(f)) | |
if write_to is None: | |
f = BytesIO() | |
im_main.save(f, **imsave_kwargs) | |
return f.get_value() | |
return im_main.save(write_to, **imsave_kwargs) | |
if __name__ == '__main__': | |
import sys, os | |
i, o = sys.argv[1:] | |
svg2ico(url=i, write_to=(o or sys.stdout.buffer)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment