代码之家  ›  专栏  ›  技术社区  ›  colinmarc

在python中服务器端SVG到PNG(或其他一些图像格式)

  •  11
  • colinmarc  · 技术社区  · 16 年前

    目前,我正在使用rsvg加载SVG(从一个字符串,而不是从一个文件)并绘制到开罗。有人知道更好的方法吗?我在应用程序的其他地方使用PIL,但我不知道如何使用PIL来实现这一点。

    4 回复  |  直到 11 年前
        1
  •  12
  •   BartoszKP    11 年前

    以下是我目前拥有的:

    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)
    
        2
  •  3
  •   Maciek Sawicki    16 年前

    ImageMagic怎么样?- http://www.imagemagick.org/script/magick-vector-graphics.php 它可以读/写从/到stdin/stdout,这样即使您不想使用文件,您也可以将其与应用程序集成。

        3
  •  2
  •   tjb    15 年前

    我已经安装了inkscape,所以我只需将过程传递给inkscape命令 inkscape -f file.svg -e file.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])
    

    我在Windows7上,在切换到Inkscape目录之前,出现了Windows5错误[拒绝访问](或类似的错误)。

        4
  •  2
  •   Matt Hampton    12 年前

    您也可以使用phantomjs进行此操作(请参见 http://phantomjs.org/screen-capture.html )

    来自壳牌:

    phantomjs rasterize.js http://ariya.github.com/svg/tiger.svg tiger.png
    

    或者从使用硒的蟒蛇身上:

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