目錄

廣告 AD

Python: 將 SVG 轉成 PNG 的三種方法!

在找圖片素材的時候,我都特別喜歡找向量圖檔

因為可以隨意地調整大小且不會變模糊

但有時候需要把 SVG 轉成 PNG

於是就有了這篇

廣告 AD

要把 SVG 轉成 PNG,雖然可以使用網路上的網站轉換

但我就是不想把我的圖片上傳上去,可能有隱私的風險

因此只好請出萬能的 Python 來幫我解決問題

下面將依序介紹三種方法:

  • CairoSVG
  • Inkscape
  • ImageMagick + Wand

CairoSVG Website


安裝:

bash

pip install CairoSVG

CairoSVG 有提供 Command Line 可以直接使用

bash

usage: cairosvg [-h] [-v] [-f {eps,pdf,png,ps,svg}] [-d DPI] [-W WIDTH] [-H HEIGHT] [-s SCALE] [-b COLOR] [-n] [-i]
                [-u] [--output-width OUTPUT_WIDTH] [--output-height OUTPUT_HEIGHT] [-o OUTPUT]
                input

Convert SVG files to other formats

positional arguments:
  input                 input filename or URL

optional arguments:
  -h, --help            show this help message and exit
  -v, --version         show program's version number and exit
  -f {eps,pdf,png,ps,svg}, --format {eps,pdf,png,ps,svg}
                        output format
  -d DPI, --dpi DPI     ratio between 1 inch and 1 pixel
  -W WIDTH, --width WIDTH
                        width of the parent container in pixels
  -H HEIGHT, --height HEIGHT
                        height of the parent container in pixels
  -s SCALE, --scale SCALE
                        output scaling factor
  -b COLOR, --background COLOR
                        output background color
  -n, --negate-colors   replace every vector color with its complement
  -i, --invert-images   replace every raster pixel with its complementary color
  -u, --unsafe          fetch external files, resolve XML entities and allow very large files (WARNING: vulnerable to
                        XXE attacks and various DoS)
  --output-width OUTPUT_WIDTH
                        desired output width in pixels
  --output-height OUTPUT_HEIGHT
                        desired output height in pixels
  -o OUTPUT, --output OUTPUT
                        output filename

或是 import 成 module 使用

一共有 5 種轉換的 function:

  • svg2eps
  • svg2pdf
  • svg2png
  • svg2ps
  • svg2svg

輸入的參數有 3 種:

  • url: 檔案路徑或是網址
  • file_obj: 檔案物件
  • bytestring: 檔案內容

Python

from cairosvg import svg2png

svg2png(url='path/to/svg.svg', write_to='path/to/png.png')

# or

with open('path/to/svg.svg', 'r') as f:
  svg2png(file_obj=f, write_to='path/to/png.png')

# or

with open('path/to/svg.svg', 'r') as f:
  svg2png(bytestring=f.read(), write_to='path/to/png.png')
注意

如果裡面有使用到 href 或是一些不安全的內嵌的話,預設是不會 render 出來,因此最後參數要加上 unsafe=True,否則不會 render。

Python

from cairosvg import svg2png

svg2png(url='path/to/svg.svg', write_to='path/to/png.png', unsafe=True)

Inkscape Website


Inkscape 是一款可以編輯向量圖片的開源程式,也支援各大主流作業系統,MacOS、Windows、Linux 都有支援,Inkscape 也有提供 Command Line 的介面可以使用,因此我們也可以安裝 Inkscape 再透過 CLI 來讓他幫我們轉換格式。

安裝的話可以到官網下載程式,並將程式的 bin 資料夾設定為環境變數,在 Windows 中預設的路徑為 C:\Program Files\Inkscape\bin


Python

import os
import subprocess

svg_file = 'path/to/svg.svg'
png_file = 'path/to/png.png'

# 取得當前 python 檔案所在路徑
cwd = os.path.dirname(os.path.realpath(__file__))

# 設定 CLI 指令
options = ['inkscape', f'--export-filename={png_file}', '--export-type=png', svg_file]

# 執行並等待執行結束
proc = subprocess.Popen(options, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd, shell=True)
outs, errs = proc.communicate()

# 印出訊息
print(errs.decode('utf-8'))

ImageMagick Website


ImageMagick 是一個開源軟體,可以對圖片編輯、轉換格式和檢視圖片,支援了大量的圖片格式,且主要透過 Command Line 來使用,今天我們要使用的是 Python 上的套件 Wand,Wand 就是對 ImageMagick 的封裝,讓大家可以透過 Python 來使用 ImageMagick。

首先要先安裝 ImageMagick 的程式,可以到官網下載安裝檔,Linux、Mac OS 和 Windows 都有支援,可以依據需求選擇下載,Windows 官方推薦下載下方的版本。安裝時記得勾選將程式加入 PATH 環境變數。

ImageMagick Download


接著要安裝 Wand

bash

 pip install Wand

使用方式:

Python

from wand.color import Color
from wand.image import Image

svg_file = 'path/to/svg.svg'
png_file = 'path/to/png.png'

# 設定背景為透明
with Color('transparent') as bg:
    # 讀 SVG
    with Image(filename=svg_file, format='svg', background=bg) as img:
        # 轉成 PNG
        png_image = img.make_blob('png32')
        # 輸出 PNG
        with open(png_file, 'wb') as out:
            out.write(png_image)

我們一共介紹了 3 種方法將 SVG 轉成 PNG

其中最推薦使用 CairoSVG 來轉換

因為相對簡單,其餘兩者都需要安裝軟體

但 Inkscape 和 ImageMagick 功能都很強大,也是很推薦使用的


廣告 AD