How do I get the picture size with PIL?

前端 未结 7 1473
粉色の甜心
粉色の甜心 2020-11-28 18:15

How do I get a size of a pictures sides with PIL or any other Python library?

相关标签:
7条回答
  • 2020-11-28 18:40

    Followings gives dimensions as well as channels:

    import numpy as np
    from PIL import Image
    
    with Image.open(filepath) as img:
        shape = np.array(img).shape
    
    0 讨论(0)
  • 2020-11-28 18:42

    Since scipy's imread is deprecated, use imageio.imread.

    1. Install - pip install imageio
    2. Use height, width, channels = imageio.imread(filepath).shape
    0 讨论(0)
  • 2020-11-28 18:43
    from PIL import Image
    
    im = Image.open('whatever.png')
    width, height = im.size
    

    According to the documentation.

    0 讨论(0)
  • 2020-11-28 18:50

    Note that PIL will not apply the EXIF rotation information (at least up to v7.1.1; used in many jpgs). A quick fix to accomodate this:

    def get_image_dims(file_path):
        from PIL import Image as pilim
        im = pilim.open(file_path)
        # returns (w,h) after rotation-correction
        return im.size if im._getexif().get(274,0) < 5 else im.size[::-1]
    
    0 讨论(0)
  • 2020-11-28 18:53

    This is a complete example loading image from URL, creating with PIL, printing the size and resizing...

    import requests
    h = { 'User-Agent': 'Neo'}
    r = requests.get("https://images.freeimages.com/images/large-previews/85c/football-1442407.jpg", headers=h)
    
    from PIL import Image
    from io import BytesIO
    # create image from binary content
    i = Image.open(BytesIO(r.content))
    
    
    width, height = i.size
    print(width, height)
    i = i.resize((100,100))
    display(i)
    
    0 讨论(0)
  • 2020-11-28 18:54

    Here's how you get the image size from the given URL in Python 3:

    from PIL import Image
    import urllib.request
    from io import BytesIO
    
    file = BytesIO(urllib.request.urlopen('http://getwallpapers.com/wallpaper/full/b/8/d/32803.jpg').read())
    im = Image.open(file)
    width, height = im.size
    
    0 讨论(0)
提交回复
热议问题