Recently, our shopping mall has been more and more widely used. But in the process of application upload, there is a problem: each application on the shelf needs to be configured with an application cover image, and the size of the cover image has a specified range of 300 * 175. And the size of the picture we make is usually larger than that. So every time I manually adjust the size, I have the idea of laziness. If I have the idea, I will start to act.
import requests as req from PIL import Image from io import BytesIO def make_thumb(url, sizes=(300, 175)): """ //Generate thumbnail of specified size :param path: Image path :param sizes: Specified size :return: No return, save the picture directly """ response = req.get(path) im = Image.open(BytesIO(response.content)) mode = im.mode if mode not in ('L', 'RGB'): if mode == 'RGBA': # Transparent pictures need white background alpha = im.split()[3] bgmask = alpha.point(lambda x: 255 - x) im = im.convert('RGB') im.paste((255, 255, 255), None, bgmask) else: im = im.convert('RGB') # Cut into squares to avoid deformation width, height = im.size if width == height: region = im else: if width > height: # h*h delta = (width - height) / 2 box = (delta, 0, delta + height, height) else: # w*w delta = (height - width) / 2 box = (0, delta, width, delta + width) region = im.crop(box) # resize thumb = region.resize((sizes[0], sizes[1]), Image.ANTIALIAS) #Save pictures filename = url.split('/')[-1] name, ext = filename.split('.') savename = name + str(sizes[0]) + '_' + str(sizes[1]) + '.' + ext thumb.save(savename, quality=100) path = r'C:\Users\HP\Desktop\luckylttory.png' make_thumb(path)
Results:
Original image:
Results:
Free download trial: free download trial: https://support.i-search.com.cn/