【问题标题】:Can you display an image inside of a python program (without using pygame)?你能在 python 程序中显示图像(不使用 pygame)吗?
【发布时间】:2014-04-30 06:04:46
【问题描述】:

我想做这样的事情:

    import image
    image.display_image('http://upload.wikimedia.org/wikipedia/commons/8/84/Example.svg')

它会以图像的形式出现。

附:我想要 PNG 或 JPEG,而不是 GIF。

【问题讨论】:

  • 您可以使用 tkinter 在画布上显示图像。类似question

标签: python image svg tkinter rsvg


【解决方案1】:

这个问题有点老了,但是由于在网上不容易找到有关如何轻松做到这一点的信息,所以我发布了这个答案,希望将来对其他人有用。

要光栅化 SVG 并将其放入 ImageTk.PhotoImage 对象中,您可以在用于 tkinter gui 的类中执行此操作:

def svgPhotoImage(self,file_path_name):
        import Image,ImageTk,rsvg,cairo
        "Returns a ImageTk.PhotoImage object represeting the svg file" 
        # Based on pygame.org/wiki/CairoPygame and http://bit.ly/1hnpYZY        
        svg = rsvg.Handle(file=file_path_name)
        width, height = svg.get_dimension_data()[:2]
        surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, int(width), int(height))
        context = cairo.Context(surface)
        #context.set_antialias(cairo.ANTIALIAS_SUBPIXEL)
        svg.render_cairo(context)
        tk_image=ImageTk.PhotoImage('RGBA')
        image=Image.frombuffer('RGBA',(width,height),surface.get_data(),'raw','BGRA',0,1)
        tk_image.paste(image)
        return(tk_image)

然后以这种方式在 Frame 小部件(例如 mainFrame)上显示图像:

tk_image=self.svgPhotoImage(filename)
mainFrame.configure(image=tk_image)

如果要保存图片,可以返回 image 而不是 tk_image 并以这种方式保存:

image.save(filename) # Image format is autodected via filename extension

【讨论】:

  • 你能根据 MIT 许可证许可代码吗?
  • 像所有 SO 帖子一样,它应该在知识共享署名-相同方式共享下获得许可。见stackoverflow.com/help/licensing
  • 如何安装 rsvg 和 cairo?
  • pip install pycairo 对于 RSVG,很难回答,因为它高度依赖于您的平台。谷歌是你的朋友。 Here's a minimal example for Windows.
  • @JeanOlivier:感谢您的回复。事情是 CC-by-sa 和 GPL,它的新版本可以被再许可,比 MIT/expat 更严格。 StackO 已根据 MIT 许可证在最近的帖子中制作了代码,但是您的帖子太旧了,因此我需要您的明确批准。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-28
  • 1970-01-01
  • 2018-01-01
  • 1970-01-01
  • 2022-01-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多