Load and show an image from the web in Python with Gtk 3?

Viewed 3418

I'm writing an app on Ubuntu 12.04 with Python and GTK 3. The problem I have is that I can't figure out how I should do to show a Gtk.Image in my app with an image file from the web.

This is as far as I have come:

from gi.repository import Gtk
from gi.repository.GdkPixbuf import Pixbuf
import urllib2

url = 'http://lolcat.com/images/lolcats/1338.jpg'
response = urllib2.urlopen(url)
image = Gtk.Image()
image.set_from_pixbuf(Pixbuf.new_from_stream(response))

I think everything is correct except the last line.

3 Answers

This will work;

from gi.repository import Gtk
from gi.repository.GdkPixbuf import Pixbuf
from gi.repository import Gio
import urllib

url = 'http://lolcat.com/images/lolcats/1338.jpg'
response = urllib.request.urlopen(url)
input_stream = Gio.MemoryInputStream.new_from_data(response.read(), None)
pixbuf = Pixbuf.new_from_stream(input_stream, None)
image = Gtk.Image()
image.set_from_pixbuf(pixbuf)

I know it is an old question, but things have changed since and this is still the first Google hit.

This works for me in GTK 4, I am using requests, no temp file needed

import requests
from gi.repository import GLib, Gtk, Gdk, GdkPixbuf

response = requests.get(f'https://randomimage.com/image.png')
content = response.content

loader = GdkPixbuf.PixbufLoader()
loader.write_bytes(GLib.Bytes.new(content))
loader.close()

Gtk.Image.new_from_pixbuf(loader.get_pixbuf())
Related