目前我正在使用rsvg从字符串中加载SVG,然后绘制到cairo上。有人知道更好的方法吗?我在我的应用程序中其他地方使用PIL,但我不知道如何使用PIL实现这个。
目前我正在使用rsvg从字符串中加载SVG,然后绘制到cairo上。有人知道更好的方法吗?我在我的应用程序中其他地方使用PIL,但我不知道如何使用PIL实现这个。
这是我目前拥有的代码:
import cairo
import rsvg
def convert(data, ofile, maxwidth=0, maxheight=0):
svg = rsvg.Handle(data=data)
x = width = svg.props.width
y = height = svg.props.height
print "actual dims are " + str((width, height))
print "converting to " + str((maxwidth, maxheight))
yscale = xscale = 1
if (maxheight != 0 and width > maxwidth) or (maxheight != 0 and height > maxheight):
x = maxwidth
y = float(maxwidth)/float(width) * height
print "first resize: " + str((x, y))
if y > maxheight:
y = maxheight
x = float(maxheight)/float(height) * width
print "second resize: " + str((x, y))
xscale = float(x)/svg.props.width
yscale = float(y)/svg.props.height
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, x, y)
context = cairo.Context(surface)
context.scale(xscale, yscale)
svg.render_cairo(context)
surface.write_to_png(ofile)
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, round(int(x)), round(int(y))
,并确保maxwidth和maxheight始终设置为一个高数字,这比0更好。我有许多高度为32000的SVG文件,这将导致内存错误。 - therealmarvconvert
2010年5月之前的版本在解释SVG方面表现非常糟糕。根据更新日志,似乎他们还没有完全解决SVG支持的问题(尽管我没有构建它来查看)。 - mswphantomjs rasterize.js http://ariya.github.com/svg/tiger.svg tiger.png
或者使用selenium从Python中:
from selenium import webdriver
driver = webdriver.PhantomJS()
driver.set_window_size(1024, 768)
driver.get('http://ariya.github.com/svg/tiger.svg')
driver.save_screenshot('tiger.png')
import subprocess
inkscape_dir=r"C:\Program Files (x86)\Inkscape"
assert os.path.isdir(inkscape_dir)
os.chdir(inkscape_dir)
subprocess.Popen(['inkscape.exe',"-f",fname,"-e",fname_png])
我使用的是Windows 7,之前出现了Windows 5错误[访问被拒绝](或类似的错误),直到我切换到inkscape目录才解决了问题。
cwd=inkscape_dir
传递给Popen
,而不是更改父进程的目录。 - Jason R. Coombs