python - temporarily retrieve an image using the requests library -


i'm writing web scraper needs scrape thumbnail of image url.

this function using, urlib library.

def create_thumb(self):     if self.url , not self.thumbnail:         image = urllib.request.urlretrieve(self.url)          # create thumbnail of dimension size         size = 350, 350         t_img = imagelib.open(image[0])         t_img.thumbnail(size)          # directory name temp image stored         # urlretrieve         dir_name = os.path.dirname(image[0])          # image name url         img_name = os.path.basename(self.url)          # save thumbnail in same temp directory         # urlretrieve got full-sized image,         # using same file extention in os.path.basename()         file_path = os.path.join(dir_name, "thumb" + img_name)         t_img.save(file_path)          # save thumbnail in media directory, prepend thumb         self.thumbnail.save(             os.path.basename(self.url),             file(open(file_path, 'rb'))) 

for various reasons need change use requests library, equivalent temp saving image?

you skip saving temporary file part , use corresponding response object directly create image:

#!/usr/bin/env python3 import urllib.request pil import image # $ pip install pillow  im = image.open(urllib.request.urlopen(url)) print(im.format, im.mode, im.size) 

here's requests analog:

#!/usr/bin/env python import requests # $ pip install requests pil import image # $ pip install pillow  r = requests.get(url, stream=true) r.raw.decode_content = true # handle spurious content-encoding im = image.open(r.raw) print(im.format, im.mode, im.size) 

i've tested pillow 2.9.0 , requests 2.7.0. should work since pillow 2.8.


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -