+ 我要发布
我发布的 我的标签 发现
浏览器扩展
斑点象@Edge

Python项目中使用Pillow裁减、压缩图片

首先安装 Pillow: install pillow Pillow官网:https://github.com/python-pillow/Pillow 加载本地图片: img = Image.open(img_path) 获取本地图片size: img_size = img.size img_w = img_size[0] img_h = img_size[1] 以裁减为正方形为例。 判断图片宽>长还是长>款,然后是横向裁减还是纵向裁减。 left = 0 top = 0 right = 0 bottom = 0 if img_w > img_h: left = int((img_w - img_h)/2) top = 0 right = left + img_h bottom = img_h elif img_h > img_w: left = 0 top = int((img_h - img_w)/2) right = img_w bottom = top + img_w if left > 0 or top > 0 or right > 0 or bottom > 0: # 裁剪后存储 # left, upper, right, lower box = (left, top, right, bottom) img_crop = img.crop(box) img_crop_path = "{}_crop.jpg".format(img_name) img_crop.save(img_crop_path) 获取裁减后的图片的缩略图,缩略图大小为 100 * 100 img_thumb = Image.open(img_crop_path) thumb_size = (100, 100) img_thumb.thumbnail(thumb_size) img_thumb_path = "{}_thumb.jpg".format(img_name) img_thumb.save(img_thumb_path)
我的笔记