일반적으로 정사각형으로 만들면 화면비율이 깨짐

그런걸 방지하기 위해서 남는 부분은 다른 색으로 칠해버림

import matplotlib.pylab as plt
from PIL import Image

def expend2square(pil_img, background_color) :  # 배경이미지 크기계산
    width, heigth = pil_img.size
    
    if width == heigth :   # 이미 정사각형
        return pil_img
    
    elif width > heigth :  # 너비가 > 높이인 경우
        result = Image.new(pil_img.mode, (width, width), background_color)
        result.paste(pil_img, (0, (width - heigth) // 2))   # x 좌표는 0, y 좌표는 이미지 중앙에 이미지 붙임
        return result
    else :          # 높이가 > 너비인 경우
        result = Image.new(pil_img.mode, (heigth, heigth), background_color)
        result.paste(pil_img, ((heigth - width) //2,0))    # x 좌표는 이미지 중앙, y 좌표는 0 에 이미지 붙임
        return result
        

def resize_with_padding(pil_img, new_size, background_color) :  # 남는부분에 색칠하기
    img = expend2square(pil_img, background_color)
    img = img.resize((new_size[0], new_size[1]), Image.ANTIALIAS)
    
    return img
    
    
    
    
img = Image.open("./image01.jpeg")
img_new = resize_with_padding(img, (300,300), (0,0,255))  # 300, 300 : 사진 크기  # 0,0,255 : RGB 

plt.imshow(img)
plt.show()

plt.imshow(img_new)
plt.show()

+ Recent posts