How do I open an image from the internet in PIL?

前端 未结 6 1998
难免孤独
难免孤独 2020-12-13 02:44

I would like to find the dimensions of an image on the internet. I tried using

from PIL import Image
import urllib2 as urllib
fd = urllib.urlopen(\"http://a/         


        
6条回答
  •  不知归路
    2020-12-13 03:28

    The urllib documentation mentions that an object returned by urlopen doesn't support seek operation.

    This module provides a high-level interface for fetching data across the World Wide Web. In particular, the urlopen() function is similar to the built-in function open(), but accepts Universal Resource Locators (URLs) instead of filenames. Some restrictions apply — it can only open URLs for reading, and no seek operations are available.

    However, the PIL.open function explicitly requires it.

    open

    Image.open(infile) => image

    Image.open(infile, mode) => image

    Opens and identifies the given image file. This is a lazy operation; the actual image data is not read from the file until you try to process the data (call the load method to force loading). If the mode argument is given, it must be "r".

    You can use either a string (representing the filename) or a file object. In the latter case, the file object must implement read, seek, and tell methods, and be opened in binary mode.

    Try using cStringIO module that converts a string into a file-like object.

    from PIL import Image
    import urllib2 as urllib
    import cStringIO
    
    fd = urllib.urlopen("http://a/b/c")
    image_file = cStringIO.StringIO(fd.read())
    im = Image.open(image_file)
    im.size
    

提交回复
热议问题