【问题标题】:Check aspect ratio of image stored on an FTP server without downloading the file in Python检查存储在 FTP 服务器上的图像的纵横比,而不用 Python 下载文件
【发布时间】:2021-08-21 20:43:39
【问题描述】:

我在 FTP 上有图像,我想在从 FTP 服务器下载图像之前检查图像的纵横比。使用 Python ftplib,有没有办法在不下载文件的情况下在 FTP 上检查图像尺寸(即宽度和高度)?

【问题讨论】:

    标签: python image ftp ftplib


    【解决方案1】:

    图像尺寸是文件内容的一部分。因此,您需要下载至少包含该信息的文件部分。这将与图像文件格式不同。但通常它会在文件的开头。

    如何使用 ftplib 实现这一点:一旦您收到足够的数据,只需开始下载并中止它。没有更聪明的方法可以在 FTP 中实现这一点。示例见Read or download 5kb of a file from FTP server in PHP or Python instead of downloading or reading whole file

    我会尝试阅读 8KB 之类的内容,这应该绰绰有余。然后您可以使用这样的代码从部分文件中检索大小: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)
    

    相关问题:Reading image EXIF data from SFTP server without downloading the file

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-15
      • 1970-01-01
      • 2021-10-26
      • 2012-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多