Convert svg file to png / ico with Python

Introduction

environment

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

Finally

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

reference

Recommended Posts

Convert svg file to png / ico with Python
Convert psd file to png in Python
Convert HEIC files to PNG files with Python
Convert PDF to image (JPEG / PNG) with Python
How to convert SVG to PDF and PNG [Python]
How to convert JSON file to CSV file with Python Pandas
Output to csv file with Python
Convert list to DataFrame with python
Until you edit an SVG file with AutoCAD to PNG.
[Python] How to convert db file to csv
Convert memo at once with Python 2to3
How to convert Python to an exe file
[Python] Convert csv file delimiters to tab delimiters
Convert Excel data to JSON with python
Convert Hiragana to Romaji with Python (Beta)
Convert FX 1-minute data to 5-minute data with Python
Convert PDF files to PNG files with GIMP
Convert Chinese numerals to Arabic numerals with Python
Sample to convert image to Wavelet with Python
[Python] Convert CSV file uploaded to S3 to JSON file with AWS Lambda
Made it possible to convert PNG to JPG with Pillow of Python
Convert DICOM to PNG with Ascending and Descending
Convert 202003 to 2020-03 with pandas
Convert PDFs to images in bulk with Python
[Python] Convert from DICOM to PNG or CSV
Convert Windows epoch values to date with python
Read CSV file with Python and convert it to DataFrame as it is
Convert the character code of the file with Python3
I want to write to a file with Python
Convert strings to character-by-character list format with python
How to convert / restore a string with [] in python
Procedure to load MNIST with python and output to png
Convert a text file with hexadecimal values to a binary file
I tried to touch the CSV file with Python
How to measure mp3 file playback time with python
Convert the image in .zip to PDF with Python
PyInstaller memorandum Convert Python [.py] to [.exe] with 2 lines
Connect to BigQuery with Python
Convert numpy int64 to python int
[Python] Convert list to Pandas [Pandas]
Convert HTML to text file
Draw netCDF file with python
Connect to Wikipedia with Python
Post to slack with Python 3
Convert Scratch project to Python
[Python] Convert Shift_JIS to UTF-8
Switch python to 2.7 with alternatives
Write to csv with Python
Convert genbank file to gff file
Download csv file with python
Convert python 3.x code to python 2.x
How to convert an array to a dictionary with Python [Application]
Convert images to sepia toning with PIL (Python Imaging Library)
[Python Kivy] How to create an exe file with pyinstaller
Convert video to black and white with ffmpeg + python + opencv
How to read an Excel file (.xlsx) with Pandas [Python]
I tried to divide the file into folders with Python
Try to decipher the garbled attachment file name with Python
Convert Excel file to text in Python for diff purposes
Convert .ipynb to .html (with BatchFile)
Link to get started with python