here2share

# Tk_image_view_url_io.py

Jul 20th, 2015
350
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.28 KB | None | 0 0
  1. # Tk_image_view_url_io.py
  2.  
  3. '''
  4. display an image from a URL using Tkinter, PIL and data_stream
  5. tested with Python27 and Python33  by  vegaseat  01mar2013
  6. '''
  7.  
  8. import io
  9. # allows for image formats other than gif
  10. from PIL import Image, ImageTk
  11. try:
  12.     # Python2
  13.     import Tkinter as tk
  14.     from urllib2 import urlopen
  15. except ImportError:
  16.     # Python3
  17.     import tkinter as tk
  18.     from urllib.request import urlopen
  19.  
  20. root = tk.Tk()
  21.  
  22. # find yourself a picture on an internet web page you like
  23. # (right click on the picture, under properties copy the address)
  24. #url = "http://www.google.com/intl/en/images/logo.gif"
  25. # or use image previously downloaded to tinypic.com
  26.  
  27. url = "http://tinyurl.com/wwwedu"
  28.  
  29. image_bytes = urlopen(url).read()
  30. # internal data file
  31. data_stream = io.BytesIO(image_bytes)
  32. # open as a PIL image object
  33. pil_image = Image.open(data_stream)
  34.  
  35. # optionally show image info
  36. # get the size of the image
  37. w, h = pil_image.size
  38. # split off image file name
  39. fname = url.split('/')[-1]
  40. sf = "{} ({}x{})".format(fname, w, h)
  41. root.title(sf)
  42.  
  43. # convert PIL image object to Tkinter PhotoImage object
  44. tk_image = ImageTk.PhotoImage(pil_image)
  45.  
  46. # put the image on a typical widget
  47. label = tk.Label(root, image=tk_image)
  48. label.pack(padx=5, pady=5)
  49.  
  50. root.mainloop()
Add Comment
Please, Sign In to add comment