2009-07-27 54 views
3

當柵格化svg文件時,我希望能夠爲生成的png文件設置寬度和高度。使用以下代碼,只有畫布被設置爲所需的寬度和高度,具有原始svg文件尺寸的實際圖像內容呈現在(500,600)畫布的左上角。如何使用librsvg調整svg圖像文件Python綁定

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") 

我應該怎麼做才能使圖像內容與開羅畫布大小相同?我試圖

svg.set_property('width', 500) 
svg.set_property('height', 500) 

,但得到

TypeError: property 'width' is not writable 

也爲蟒蛇的librsvg約束力的文件似乎是極爲罕見的,只有一些隨機碼在開羅現場片段。

回答

6

librsvg中有一個resize function,但不建議使用。

設立在開羅scale matrix更改圖紙的尺寸:

  • 設置你的開羅上下文
  • 縮放變換矩陣與.render_cairo()方法
  • 寫得出你的SVG你表面PNG
+1

將重新調整在原始矢量圖的數據丟失已經柵格圖像的結果? – btw0 2009-07-27 11:19:31

2

這是對我工作的代碼。 它實現了由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())