请求下载图片逻辑, 并按尺寸保存
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) """