下载图片并转变成特定大小

# 下载图片
def download_img(save_path, img_url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36'
    }
    r = requests.get(img_url, headers=headers, stream=True)
    # print(r.status_code) # 返回状态码
    if r.status_code == 200:
        # 截取图片文件名

        with open(save_path, 'wb') as f:
            f.write(r.content)
        return True


# 修改图片,上传到服务器
def get_uploadimg(path, new_path):
    img = Image.open(path)
    print(img.size)
    width = img.size[0]
    height = img.size[1]
    if width <= 600:
        print(f'宽度小于600,不变')
        new_img = img.resize((width, height))
        print(new_img.size)
        if new_img.mode == "P":
            new_img = new_img.convert('RGB')
        new_img.save(new_path)
    else:
        print('宽度大于600,等比例收缩')
        # 长度改为600,宽度按比例变化
        new_height = int(height * (float(600 / width)))
        new_img = img.resize((600, new_height))
        print(new_img.size)
        if new_img.mode == "P":
            new_img = new_img.convert('RGB')
        new_img.save(new_path)


tree = etree.HTML(content)
picture = tree.xpath('//img//@src')
picture_name = tree.xpath('//img//@alt')
for i in range(len(picture_name)):
    base_path='D:\\beifangzhongzhi\zhongye\chanpin\kuangdao\kuangkupic\\'
    save_path = base_path+picture_name[i] + '.jpg'
    img_url = picture[i]
    new_path = save_path.split('.jpg')[0]+'_new.jpg'
    print(f'save_path:{save_path}')
    print(f'img_url:{img_url}')
    print(f'new_path:{new_path}')
    download_img(save_path, img_url)
    get_uploadimg(save_path, new_path)

 

posted @ 2023-06-06 16:41  布都御魂  阅读(18)  评论(0编辑  收藏  举报