加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 通过应用transform – reduce size来简化SVG

发布时间:2020-12-16 22:17:36 所属栏目:Python 来源:网络整理
导读:我经常有一些像这样的结构的SVG: 我想直接将translate应用于坐标并删除tranform-attribute: 你知道一个简化SVG的脚本/程序吗?还是用于解析SVG的python-snipplet? 这个脚本适用于我的特殊情况,但我想要一个总是有效的: #http://epydoc.sourceforge.net/s

我经常有一些像这样的结构的SVG:

我想直接将translate应用于坐标并删除tranform-attribute:

你知道一个简化SVG的脚本/程序吗?还是用于解析SVG的python-snipplet?

这个脚本适用于我的特殊情况,但我想要一个总是有效的:

#http://epydoc.sourceforge.net/stdlib/xml.dom.minidom.Element-class.html
from xml.dom.minidom import parse,parseString
import re

f = open('/home/moose/mathe/svg/Solitaire-Board.svg','r')

xmldoc = parse(f)

p = re.compile('translate(([-d.]+),([-d.]+))',re.IGNORECASE)

for node in xmldoc.getElementsByTagName('svg:g'):
  transform_dict = node.attributes["transform"]
  m = p.match(transform_dict.value)
  if m:
    x = float(m.group(1))
    y = float(m.group(2))
  child_rectangles = node.getElementsByTagName('svg:rect') 
  for rectangle in child_rectangles:
    x_dict = rectangle.attributes["x"]
    y_dict = rectangle.attributes["y"]
    new_x = float(x_dict.value) + x
    new_y = float(y_dict.value) + y
    rectangle.setAttribute('x',str(new_x))
    rectangle.setAttribute('y',str(new_y))
  node.removeAttribute('transform')

print xmldoc.toxml()

我认为如果可以删除transform属性,svg的大小可以大大减少而不会降低质量.
如果该工具能够降低坐标精度,那么明智地删除不必要的区域,组和样式就会很棒.

最佳答案
我建议使用lxml.它非常快,并且有很多不错的功能.如果正确声明了svg名称空间前缀,则可以解析示例.你可以很容易地做到这一点:

>>> svg = '

现在您可以使用lxml.etree(或xml.etree.ElementTree)解析它:

>>> doc = etree.fromstring(svg)

如果你使用lxml,你可以利用XPath:

>>> ns = {'svg': 'http://www.w3.org/2000/svg'}

>>> doc.xpath('//svg:g/@transform',namespaces=ns)
<<< ['translate(-251.5,36.5)']

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读