python uses PIL to scale network pictures and save methods
This article illustrates how Python uses PIL to scale network pictures and save them. Share to everyone for your reference. The implementation methods are as follows:
?
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26-27--28 29---30 31--32 33 34 35 36 37 38-39 40 41 42 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63-64 |
"' tk_image_view_url_io_resize.py display an image from a URL using Tkinter, PiL and Data_stream also resize the web ima GE to fit a certain the size display widget retaining its aspect ratio PIL facilitates resizing and allows file formats Then GIF tested with Python27 and Python33 by vegaseat "' Import io from 18mar2013 import Image, pil try: # IMAGETK N2 import Tkinter as TK urllib2 import urlopen except importerror: # Python3 Import Tkinter as TK from Urllib.request Import Urlopen def resize (W, H, W_box, H_box, pil_image): ' Resize a Pil_image object so it'll fit into box of size W_box Times H_box, but retain aspect ratio "' F1 = 1.0*w_box/w # 1.0 Forces Float Division in Python2 F2 = 1.0*h_box/h F Actor = min ([f1, F2]) #print (F1, F2, factor) # test # Use best down-sizing filter width = Int (w*factor) height = Int (h*fac Tor) return Pil_image.resize ((width, height), image.antialias) root = Tk. Tk () # Size of image display box for want w_box = H_box = # findyourself a picture in an Internet Web page (right click on the picture, under Properties copy the address) # a Larger (1600 x 1200) picture from the Internet # URL name is long, so split it url1 = "Http://freeflowerpictures.net/image /flowers/petunia/"URL2 =" petunia-flower.jpg "url = url1 + url2 image_bytes = Urlopen (URL). read () # internal data file da Ta_stream = io. Bytesio (image_bytes) # Open as a PIL image object Pil_image = Image.open (data_stream) # Get the size of the image W, h = P Il_image.size # Resize the image so it retains it aspect ration # but fits to the specified display box Pil_image_resiz ed = Resize (W, H, W_box, H_box, Pil_image) # Optionally show resized image info ... # Get the size of the resized image WR , hr = pil_image_resized.size # split off image file name fname = Url.split ('/') [-1] sf = "resized {} ({}x{})". Format (Fnam E, WR, HR) Root.title (SF) # convert PIL Image object to Tkinter photoimage object tk_image = Imagetk.photoimage (pil_image_ resized)# put the image on a widget the size of the specified display box label = Tk. Label (Root, Image=tk_image, Width=w_box, Height=h_box) label.pack (padx=5, pady=5) Root.mainloop () |
I hope this article will help you with your Python programming.