最近我们商城的应用越来越丰富了。但是在上传应用的过程中,我们遇到了这样一个问题:每一个上架的应用都需要配置一个应用封面图,并且封面图的尺寸有一个指定的范围:300*175。而我们制作的图片一般都大于这个尺寸。于是每次手动调整大小的时候,又萌生了偷懒的念头。有了想法,就开始行动吧。importrequestsasreqfromPILimportImagefromioimportBytesIOdefmake_thumb(url,sizes=(300,175)):"""生成指定大小的缩略图:parampath:imagepath:paramsizes:specifiedsize:return:不返回,直接保存图像"""response=req.get(path)im=Image.open(BytesIO(response.content))mode=im.modeifmodenotin('L','RGB'):ifmode=='RGBA':#透明图片需要加白色背景alpha=im.split()[3]bgmask=alpha.point(lambdax:255-x)im=im.convert('RGB')im.paste((255,255,255),None,bgmask)else:im=im.convert('RGB')#裁剪成方形图片避免变形width,height=im.sizeifwidth==height:region=imelse:如果宽度>高度:#h*hdelta=(width-height)/2box=(delta,0,delta+height,height)else:#w*wdelta=(height-width)/2box=(0,增量,宽度,增量+宽度)region=im.crop(box)#调整大小thumb=region.resize((sizes[0],sizes[1]),Image.ANTIALIAS)#saveimagefilename=url.split('/')[-1]name,ext=filename.split('.')savename=name+str(sizes[0])+'_'+str(sizes[1])+'.'+extthumb.save(savename,quality=100)path=r'C:\Users\HP\Desktop\luckylttory.png'make_thumb(path)结果显示:原图:结果图:免费下载试用:https://support.i-search.com.cn/
