python 实现 请求网址保存图片, 并返回指定尺寸的图片大小

请求下载图片逻辑, 并按尺寸保存

 

def get_img(self, url, category_num):
    # 取到图片,并保存。
    res_title = url.split("/")[-1]
    path_ = '/img/crawl/' + str(category_num) + "/"
    if not os.path.exists(path_):
        os.makedirs(path_)  # 创建一个文件,用来存储图片
    try:
        response = requests.get(url=url)
        path = path_ + res_title  # 给图片取个名字

        with open(path + ".png", 'wb') as f:
            f.write(response.content)
            print('正在下载:  {}'.format(res_title))

        # 设计 输出图片尺寸的
        produceImage(path + ".png", path + ".png")
        return path

    except:
        # 没有 就随机给一张图片
        img_url = '/img/default/' + str(choice([i for i in range(30)])) + '.jpg'
        return img_url

 

# 处理图片, 输出为指定尺寸的
def produceImage(file_in,  file_out):
    width = 230
    height = 180
    image = Image.open(file_in)
    resized_image = image.resize((width, height), Image.ANTIALIAS)
    resized_image.save(file_out)

 

源码详解:

"""
'''
filein: 输入图片
fileout: 输出图片
width: 输出图片宽度
height:输出图片高度
type:输出图片类型(png, gif, jpeg...)
'''
def ResizeImage(filein, fileout, width, height, type):
  img = Image.open(filein)
  out = img.resize((width, height),Image.ANTIALIAS) #resize image with high-quality
  out.save(fileout, type)
  
"""
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值