1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| import requests from io import BytesIO from PIL import Image import numpy as np import cv2
def crop_img_on_ratio(img, ratio): """按比例裁减图片""" ratio_w, ratio_h = ratio img_w, img_h = img.size if img_h/img_w >= ratio_h/ratio_w: h = int(img_w*ratio_h/ratio_w) box = (0, int((img_h-h)/2), img_w, int((img_h+h)/2)) else: w = int(img_h*ratio_w/ratio_h) box = (int((img_w-w)/2), 0, int((img_w+w)/2), img_h) return img.crop(box)
def mix_img_icon(img, icon): """图片图标合成,居中""" img_w, img_h = img.size icon_w, icon_h = icon.size box = (int((img_w-icon_w)/2), int((img_h-icon_h)/2)) if icon.format == 'PNG': img.paste(icon, box=box, mask=icon) else: img.paste(icon, box=box)
def get_blur_image(img): """宽高比不为1的图片处理成两端模糊填充的正方形""" w, h = img.size a = max(w, h) crop_img = crop_img_on_ratio(img, (1, 1)) scale_img = crop_img.resize((a, a), resample=Image.ANTIALIAS) cv_img = cv2.cvtColor(np.asarray(scale_img), cv2.COLOR_RGB2BGR) cv_gb_img = cv2.GaussianBlur(cv_img, (0, 0), 7) gb_img = Image.fromarray(cv2.cvtColor(cv_gb_img, cv2.COLOR_BGR2RGB)) mix_img_icon(gb_img, img) return gb_img
if __name__ == "__main__": source_img = Image.open('/path/to/source_image.jpg')
source_img = Image.open(BytesIO(requests.get('http://url/for/source_image.jpg').content)) blur_img = get_blur_image(source_img)
gb_img.save('/path/to/target_image.jpg', "JPEG")
img_file = BytesIO() image.save(img_file, "JPEG")
|