如何在Python程序中显示图像(不使用pygame)?
我想做一些像这样的事情:
import image
image.display_image('http://upload.wikimedia.org/wikipedia/commons/8/84/Example.svg')
然后它会变成一张图片。
附注:我想要的是PNG或JPEG格式,不要GIF格式。
1 个回答
5
这个问题虽然有点老,但网上关于如何简单实现这个功能的信息并不多,所以我想分享这个答案,希望能对将来的人有帮助。
要把SVG格式的图像转换成位图,并放入ImageTk.PhotoImage对象中,你可以在一个用于tkinter图形界面的类里这样做:
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