본문 바로가기
💻CODING/python

[py] 이미지 사이즈 줄이기

by 코딩하는 갓디노 2022. 9. 30.

[py] 이미지 사이즈 줄이기

 

파이썬을 이용하여
이미지 사이즈를 일괄 수정하는 방법입니다.

 

예제는 스타트 코딩, 파이썬 크롤링 강의를 들으면서 공부한 내용입니다.

 

이미지 조정 라이브러리

pillow

pip install pillow #이미지 처리 라이브러리

 

이미지 사이즈 조정 코드

  • 이미지 열때, 저장할때 경로가 필요합니다.
import os
from PIL import Image

# 정리할 확장자 리스트
extention_list = ['.jpg', '.png', '.gif']

#해당 이미지 폴더
target = 'C:/project/python/랜덤이미지'

#만들 폴더
destination = os.path.join(target, 'small')

#폴더가 없다면 폴더 생성
if not os.path.exists(destination):
    os.mkdir(destination)

#현재 폴더 내 모든 파일 출력
file_list = os.listdir(target)

#반복문 통해 각 파일의 확장자 확인
for file in file_list:
    name, ext = os.path.splitext(file)
    if ext in extention_list:
        #이미지 열기
        img_path = os.path.join(target, file) 
        img = Image.open(img_path) # 이미지 객체 반환

        #이미지 크기 수정
        width = int(img.width * 0.5)
        height = int(img.height * 0.5)
        resize = img.resize((width, height)) #튜플 형태로 width, height 넘기기

        #이미지 저장
        save_path = os.path.join(destination, file)
        resize.save(save_path)

 

구현 화면

 

반응형

댓글