일부 변환은 품질 손실이나 기능 제한이 있을 수있고(예 GIF -> JPG 변환시 애니메이션정보가 손실), 모든 조합이실용적이지는 않다(예: BMP는 용량이 커서 잘 사용하지 않음)
이제 실행해 보자
import os
from PIL import Image
def convert_image_format(folder_path, from_format, to_format):
"""
지정된 형식의 이미지를 다른 형식으로 변환합니다.
:param folder_path: 이미지가 있는 폴더 경로
:param from_format: 원본 이미지 형식 (예: 'webp', 'jpg', 'png')
:param to_format: 변환할 이미지 형식 (예: 'webp', 'jpg', 'png')
"""
# 형식에서 점 제거 및 소문자로 변환
from_format = from_format.lower().strip('.')
to_format = to_format.lower().strip('.')
if not os.path.exists(folder_path):
print(f"폴더를 찾을 수 없습니다: {folder_path}")
return
# 지원하는 형식 확인
supported_formats = {'webp', 'jpg', 'jpeg', 'png'}
if from_format not in supported_formats or to_format not in supported_formats:
print("지원하지 않는 형식입니다. webp, jpg, png 형식만 지원합니다.")
return
for filename in os.listdir(folder_path):
if filename.lower().endswith(f'.{from_format}'):
input_path = os.path.join(folder_path, filename)
output_filename = os.path.splitext(filename)[0] + f'.{to_format}'
output_path = os.path.join(folder_path, output_filename)
try:
with Image.open(input_path) as img:
# PNG로 변환할 때는 RGBA 모드 유지, 그 외에는 RGB로 변환
if to_format.lower() == 'png':
if img.mode != 'RGBA':
img = img.convert('RGBA')
else:
img = img.convert('RGB')
# 이미지 저장
if to_format.lower() == 'jpg':
img.save(output_path, 'JPEG', quality=95)
else:
img.save(output_path, to_format.upper())
print(f"변환 완료: {filename} -> {output_filename}")
# 원본 파일 삭제
os.remove(input_path)
print(f"원본 파일 삭제됨: {filename}")
except Exception as e:
print(f"파일 변환 중 오류 발생 {filename}: {e}")
# 사용 예시
if __name__ == "__main__":
folder_path = r"c:\Users\폴더" # 폴더 경로를 지정하세요
# WebP -> JPG 변환
convert_image_format(folder_path, 'webp', 'jpg')
# PNG -> JPG 변환
# convert_image_format(folder_path, 'png', 'jpg')
# WebP -> PNG 변환
# convert_image_format(folder_path, 'webp', 'png')
폴더 내에 있는
모든 webp 파일을 jpg 파일로 변환 시킨다
추가로 코드에서는 지정한 형식(`from_format`)의 파일만 검사하고 변환하기 때문에,