該賞金過期5天。這個問題的答案有資格獲得 50聲望獎勵。 DuckQueen正在尋找信譽良好的來源的答案。
所以我想從具有目標解析度 WxH 的 python 代碼渲染 SVG(將 SVG 文本作為 str,就像我動態生成的這樣):
<svg width="200" height="200" viewBox="0 0 220 220"
xmlns="http://www.w3.org/2000/svg">
<filter id="displacementFilter">
<feTurbulence type="turbulence" baseFrequency="0.05"
numOctaves="2" result="turbulence"/>
<feDisplacementMap in2="turbulence" in="SourceGraphic"
scale="50" xChannelSelector="R" yChannelSelector="G"/>
</filter>
<circle cx="100" cy="100" r="100"
style="filter: url(#displacementFilter)"/>
</svg>
成 png 影像。如何在 Python 中做這樣的事情?
uj5u.com熱心網友回復:
你可以使用開羅SVG
CairoSVG 在 PyPI 上可用,你可以用 pip 安裝它:
pip3 install cairosvg
在您的代碼中:
import cairosvg
width = 640
height = 480
cairosvg.svg2png(url='logo.svg', write_to='image.png', output_width=width, output_height=height)
uj5u.com熱心網友回復:
| 解決方案 | 過濾器有效嗎? | 阿爾法通道? | 直接從python呼叫? |
|---|---|---|---|
| cairosvg | 不* | 是的 | 是的 |
| svglib | 不 | 不 | 是的 |
| 水墨畫 | 是的 | 是的 | 不** |
* 來自cairosvg 檔案:
僅支持
feOffset,feBlend和feFlood過濾器。
** 通過子行程呼叫外部程式
注意:我為所有示例影像添加了純白色背景,以便在深色背景上更容易看到它們,除非上表中有說明,否則原件確實具有透明背景
cairosvg

import cairosvg
# read svg file -> write png file
cairosvg.svg2png(url=input_svg_path, write_to=output_png_path, output_width=width, output_height=height)
# read svg file -> png data
png_data = cairosvg.svg2png(url=input_svg_path, output_width=width, output_height=height)
# svg string -> write png file
cairosvg.svg2png(bytestring=svg_str.encode(), write_to=output_png_path, output_width=width, output_height=height)
# svg string -> png data
png_data = cairosvg.svg2png(bytestring=svg_str.encode(), output_width=width, output_height=height)
svglib

from svglib.svglib import svg2rlg
from reportlab.graphics import renderPM
# read svg -> write png
renderPM.drawToFile(svg2rlg(input_svg_path), output_png_path, fmt='PNG')
水墨畫

此處為 CLI 選項的完整檔案
import os
inkscape = ... # path to inkscape executable
# read svg file -> write png file
subprocess.run([inkscape, '--export-type=png', f'--export-filename={output_png_path}', f'--export-width={width}', f'--export-height={height}', input_svg_path])
# read svg file -> png data
result = subprocess.run([inkscape, '--export-type=png', '--export-filename=-', f'--export-width={width}', f'--export-height={height}', input_svg_path], capture_output=True)
# (result.stdout will have the png data)
# svg string -> write png file
subprocess.run([inkscape, '--export-type=png', f'--export-filename={output_png_path}', f'--export-width={width}', f'--export-height={height}', '--pipe'], input=svg_str.encode())
# svg string -> png data
result = subprocess.run([inkscape, '--export-type=png', '--export-filename=-', f'--export-width={width}', f'--export-height={height}', '--pipe'], input=svg_str.encode(), capture_output=True)
# (result.stdout will have the png data)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/343508.html
