How to do it
When I googled lightly, there were many examples of converting in the order of svg-> png-> ico.
svg -> png
It seems that conversion of svg-> png can be done by using cairosvg.
Installation
$ pip install cairosvg
It seems that the executable file is included, so execute it as it is.
And an error ...
$ cairosvg sample.svg -o sample.png
Traceback (most recent call last):
File "/Users/tommarute/miniconda3/envs/py366/bin/cairosvg", line 6, in <module>
from cairosvg.__main__ import main
File "/Users/tommarute/miniconda3/envs/py366/lib/python3.6/site-packages/cairosvg/__init__.py", line 42, in <module>
from . import surface # noqa isort:skip
File "/Users/tommarute/miniconda3/envs/py366/lib/python3.6/site-packages/cairosvg/surface.py", line 28, in <module>
from .defs import (
File "/Users/tommarute/miniconda3/envs/py366/lib/python3.6/site-packages/cairosvg/defs.py", line 24, in <module>
from .bounding_box import calculate_bounding_box, is_non_empty_bounding_box
File "/Users/tommarute/miniconda3/envs/py366/lib/python3.6/site-packages/cairosvg/bounding_box.py", line 26, in <module>
from .features import match_features
File "/Users/tommarute/miniconda3/envs/py366/lib/python3.6/site-packages/cairosvg/features.py", line 25, in <module>
LOCALE = locale.getdefaultlocale()[0] or ''
File "/Users/tommarute/miniconda3/envs/py366/lib/python3.6/locale.py", line 562, in getdefaultlocale
return _parse_localename(localename)
File "/Users/tommarute/miniconda3/envs/py366/lib/python3.6/locale.py", line 490, in _parse_localename
raise ValueError('unknown locale: %s' % localename)
ValueError: unknown locale: UTF-8
Somehow the locale seems to be unknown
Try to specify
$ LC_CTYPE="ja_JP.UTF-8" cairosvg sample.svg -o sample.png
I got it.
$ ls -ltr
total 16
-rw-r--r-- 1 tommarute user 348 Nov 17 22:15 sample.svg
-rw-r--r-- 1 tommarute user 1473 Nov 17 22:16 sample.png
png -> ico
It seems that png-> ico can be used with pillow.
Installation
$ pip install pillow
There is no executable file here, so use it as a library.
In [1]: from PIL import Image
In [2]: fn = r'sample.png'
In [3]: img = Image.open(fn)
In [4]: img.save('favicon.ico')
In [5]:
I got it.
$ ls -ltr
total 48
-rw-r--r-- 1 tommarute user 348 Nov 17 22:15 sample.svg
-rw-r--r-- 1 tommarute user 1473 Nov 17 22:16 sample.png
-rw-r--r-- 1 tommarute user 12993 Nov 17 22:20 favicon.ico
It's a little like that, so let's make a slightly better script.
import sys
import os
os.environ['LC_CTYPE'] = "ja_JP.UTF-8"
import cairosvg
from PIL import Image
def run(svg, ico):
print(f'svg = {svg}')
print(f'ico = {ico}')
png = f'{svg}.png'
cairosvg.svg2png(url=svg, write_to=png)
img = Image.open(png)
img.save(ico)
print('Deleting temporary png file.')
os.unlink(png)
print('svg2ico has finished normally.')
def main():
args = sys.argv
run(args[1], args[2])
if __name__ == '__main__':
main()
The end
Recommended Posts