How do I get a size of a pictures sides with PIL or any other Python library?
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
Since scipy
's imread
is deprecated, use imageio.imread
.
pip install imageio
height, width, channels = imageio.imread(filepath).shape
from PIL import Image
im = Image.open('whatever.png')
width, height = im.size
According to the documentation.
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]
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)
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