GetImage.py 文件源码

python
阅读 18 收藏 0 点赞 0 评论 0

项目:CorpBot.py 作者: corpnewt 项目源码 文件源码
def download(url, ext : str = "jpg", sizeLimit : int = 8000000, ua : str = 'CorpNewt DeepThoughtBot'):
    """Download the passed URL and return the file path."""
    # Set up a temp directory
    dirpath = tempfile.mkdtemp()
    tempFileName = url.rsplit('/', 1)[-1]
    # Strip question mark
    tempFileName = tempFileName.split('?')[0]
    imagePath = dirpath + "/" + tempFileName

    try:
        rImage = requests.get(url, stream = True, headers = {'User-agent': ua})
    except:
        remove(dirpath)
        return None

    with open(imagePath, 'wb') as f:
        for chunk in rImage.iter_content(chunk_size=1024):
            if chunk:
                f.write(chunk)

    # Check if the file exists
    if not os.path.exists(imagePath):
        remove(dirpath)
        return None

    # Let's make sure it's less than the passed limit
    imageSize = os.stat(imagePath)

    while int(imageSize.st_size) > sizeLimit:
        try:
            # Image is too big - resize
            myimage = Image.open(imagePath)
            xsize, ysize = myimage.size
            ratio = sizeLimit/int(imageSize.st_size)
            xsize *= ratio
            ysize *= ratio
            myimage = myimage.resize((int(xsize), int(ysize)), Image.ANTIALIAS)
            myimage.save(imagePath)
            imageSize = os.stat(imagePath)
        except Exception:
            # Image too big and can't be opened
            remove(dirpath)
            return None
    try:
        # Try to get the extension
        img = Image.open(imagePath)
        ext = img.format
        img.close()
    except Exception:
        # Not something we understand - error out
        remove(dirpath)
        return None

    if ext:
        os.rename(imagePath, '{}.{}'.format(imagePath, ext))
        return '{}.{}'.format(imagePath, ext)
    else:
        return imagePath
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号