Check aspect ratio of image stored on an FTP server without downloading the file in Python

Question:

I have images on FTP and I would like to check the image aspect ratio before downloading the image from the FTP server. Using Python ftplib, is there a way to check image dimensions (ie width and height) on FTP without downloading the file?

Asked By: jadeidev

||

Answers:

The image dimensions are part of the file contents. So you need to download at least the part of the file that contains that information. That would differ with the image file format. But usually it will be at the very beginning of the file.

How to implement this with ftplib: Just start a download and abort it, once you receive enough data. There’s no smarter way to implement this in FTP. For an example, see Read or download 5kb of a file from FTP server in PHP or Python instead of downloading or reading whole file.

I’d try reading something like 8KB, what should ne more than enough. Then you can use a code like this to retrieve the size from the partial file: Get Image size WITHOUT loading image into memory

from PIL import Image
from ftplib import FTP
from io import BytesIO

ftp = FTP()
ftp.connect(host, user, passwd)
 
cmd = "RETR {}".format(filename)
f = BytesIO()
size = 8192
aborted = False

def gotdata(data):
    f.write(data)
    while (not aborted) and (f.tell() >= size):
        ftp.abort()
        aborted = True

try:
    ftp.retrbinary(cmd, gotdata)
except:
    # An exception when transfer is aborted is expected
    if not aborted:
        raise

f.seek(0)
im = Image.open(f)

print(im.size)

Related question: Reading image EXIF data from SFTP server without downloading the file

Answered By: Martin Prikryl
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.