btw*_*tw0 5 python cairo librsvg
当光栅化svg文件时,我希望能够为生成的png文件设置宽度和高度.使用以下代码,仅将画布设置为所需的宽度和高度,具有原始svg文件尺寸的实际图像内容将呈现在(500,600)画布的左上角.
import cairo
import rsvg
WIDTH, HEIGHT = 500, 600
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, WIDTH, HEIGHT)
ctx = cairo.Context(surface)
svg = rsvg.Handle(file="test.svg")
svg.render_cairo(ctx)
surface.write_to_png("test.png")
Run Code Online (Sandbox Code Playgroud)
我该怎么做才能使图像内容与cairo canvas相同?我试过了
svg.set_property('width', 500)
svg.set_property('height', 500)
Run Code Online (Sandbox Code Playgroud)
但得到了
TypeError: property 'width' is not writable
Run Code Online (Sandbox Code Playgroud)
librsvg python绑定的文档似乎非常罕见,只有一些随机代码片段在cairo网站上.
这是适合我的代码。它实现了上面 Luper 的答案:
import rsvg
import cairo
# Load the svg data
svg_xml = open('topthree.svg', 'r')
svg = rsvg.Handle()
svg.write(svg_xml.read())
svg.close()
# Prepare the Cairo context
img = cairo.ImageSurface(cairo.FORMAT_ARGB32,
WIDTH,
HEIGHT)
ctx = cairo.Context(img)
# Scale whatever is written into this context
# in this case 2x both x and y directions
ctx.scale(2, 2)
svg.render_cairo(ctx)
# Write out into a PNG file
png_io = StringIO.StringIO()
img.write_to_png(png_io)
with open('sample.png', 'wb') as fout:
fout.write(png_io.getvalue())
Run Code Online (Sandbox Code Playgroud)