你能在python程序中显示一个图像(不使用pygame)吗? [英] Can you display an image inside of a python program (without using pygame)?

查看:305
本文介绍了你能在python程序中显示一个图像(不使用pygame)吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做类似的事情:

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

它会以图像形式出现。

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

P.S. I want PNG or JPEG, not GIFs.

推荐答案

这个问题有些陈旧,但有关如何轻松完成此操作的信息在网上很容易找到,我发布这个答案,希望将来对其他人有用。

This question is somewhat old, but as info on how to do this easily isn't easy to find online, I'm posting this answer in hope it can be useful to others in the future.

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

To raster a SVG and put it into a ImageTk.PhotoImage object you can do this inside a class used for a 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)这样:

Then display the image on a Frame widget (e.g. mainFrame) this way:

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

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

If you want to save the picture you can return image instead of tk_image and save it this way:

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

这篇关于你能在python程序中显示一个图像(不使用pygame)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆