이미지 변환도 거의 완성…
이미지 확장자 변환해주는 프로세스 중에 멀티 프로세스가 끝났습니다.
원래 싱글 프로세스 개발한 다음에 멀티 프로세스를 개발하는데.. 싱글 프로세스가 개발이 끝난 줄 알고 멀티 프로세스 개발하는 도중
원본 이미지가 저장되어 있는 폴더랑 확장자를 변환한 이미지를 저장할 폴더가 같은 경우, 서브 폴더를 만들건지 물어보는 옵션을 빼먹었더라구요.. 어쩐지 너무 빨리 끝나더라
그래서 그건 내일이나 내일 모레 중으로 마저 완성해서 Alpha v1.2.0 으로 버전을 올릴 생각입니다.
지금 당장 내일 수II랑 생명과학 시험을 봐야하느라 지금은 힘들거 같네용
아래는 이미지 확장자 변환 멀티 프로세스 전체 코드입니당
뭔가 할 얘기만 쏼랑쏼랑 하고 마는건 좀 그래서 코드라도 올려봐요
from PIL import Image
import os, json
def print_divider():
print()
print("-" * 30)
print()
# Convert image to target format and save
def convert_and_save(input_file_path, output_folder, target_format):
file_name, extension = os.path.splitext(os.path.basename(input_file_path))
extension = extension.strip(".").lower()
output_image_path = os.path.join(output_folder, f"{file_name}.{target_format}")
# If the format of original image is same as target format: skip conversion
if extension == target_format:
return False
try:
with Image.open(input_file_path) as img:
if target_format in ["jpg", "jpeg"]:
target_format = "jpeg"
img = img.convert("RGB")
img.save(output_image_path, format=target_format)
return True
except Exception as e:
print(f"Error converting {os.path.basename(input_file_path)}: {e}")
return False
# Get the path of the folder where images are saved
def get_input_folder():
print("Enter the path of the folder where original images are saved.")
while True:
input_folder = input("> ").strip().strip('"').strip("'")
if not os.path.isdir(input_folder):
print(f"Cannot find the folder from: {input_folder}\n")
continue
break
return input_folder
# Get the path of the folder where converted images will be saved
def get_output_folder():
print("\nEnter the output folder where converted images will be saved.")
while True:
output_folder = input("> ").strip().strip('"').strip("'")
# Simple check to prevent saving to very sensitive root directories
if output_folder in ["", "/"]:
print("Cannot save converted images to the root directory.")
continue
break
return output_folder
# Get target format
def get_target_format():
try:
with open("info.json", "r") as info_file:
info_data = json.load(info_file)
except (FileNotFoundError, json.JSONDecodeError):
print("\nWarning: info.json not found or corrupted. Using default supported formats.")
info_data = {"supported_formats": ["jpg", "jpeg", "png", "webp"]}
supported_formats = info_data.get("supported_formats", ["jpg", "jpeg", "png", "webp"])
print("\nEnter the target image format." \
"\nEnter 'Formats' to see supported formats.")
while True:
target_format = input("> ").strip().strip(".").lower()
if target_format == "formats":
print(f"\n[ Supported Formats ]\n[ {', '.join(supported_formats).upper()} ]\n")
continue
elif target_format not in supported_formats:
print(f"\nInvalid command or Unsupported format: {target_format}")
continue
break
return target_format
# Run conversion
def run_convert():
"""Handles the main logic for gathering paths, formats, and performing conversion."""
input_folder = get_input_folder()
output_folder = get_output_folder()
target_format = get_target_format()
# Initialize a set to collect unique original extensions
original_extensions = set()
# The required sorting order for output, dynamically loaded from info.json
try:
with open("info.json", "r") as info_file:
info_data = json.load(info_file)
sort_order = [fmt.upper() for fmt in info_data.get("supported_formats", [])]
except (FileNotFoundError, json.JSONDecodeError):
print("\nWarning: Failed to load info.json for dynamic sorting order. Using default order.")
sort_order = [ "JPG", "JPEG", "PNG", "WEBP" ]
# If the path of input folder and out folder are same: ask if make subfolder
if os.path.abspath(input_folder) == os.path.abspath(output_folder):
print("\nDo you want to make a subfolder? (Y/N)")
while True:
subfolder = input("> ").strip().lower()
if subfolder not in ["y", "n"]:
print("Invalid Input. Please enter Y or N")
continue
break
# If user wants to make a subfolder: make subfolder and save converted images there
if subfolder == "y":
# Set the output folder to the new subfolder
output_folder = os.path.join(output_folder, "Converted Images")
os.makedirs(output_folder, exist_ok=True)
print_divider()
for file in os.listdir(input_folder):
if file.lower().endswith((".jpg", ".jpeg", ".png", ".webp")):
_, ext = os.path.splitext(file)
input_image_path = os.path.join(input_folder, file)
# Add only if conversion is actually performed
if convert_and_save(input_image_path, output_folder, target_format):
original_extensions.add(ext[1:].upper())
# If user does not want to make a subfolder: ask if overwrite original images
else:
print("\nDo you want to overwrite the original images? (Y/N)")
while True:
overwrite = input("> ").strip().lower()
if overwrite not in ["y", "n"]:
print("Invalid Input. Please enter Y or N")
continue
break
# If user wants to overwrite original images: save temporary converted images, delete original images, and rename temporary images
if overwrite == "y":
print_divider()
for file in os.listdir(input_folder):
if file.lower().endswith((".jpg", ".jpeg", ".png", ".webp")):
_, ext = os.path.splitext(file)
input_image_path = os.path.join(output_folder, file)
original_name, _ = os.path.splitext(os.path.basename(input_image_path))
temp_path = os.path.join(output_folder, f"{original_name}_temp.{target_format}")
try:
with Image.open(input_image_path) as img:
if target_format in ["jpg", "jpeg"]:
target_format = "jpeg"
img = img.convert("RGB")
img.save(temp_path, format=target_format)
# Replace original file with the new one
os.remove(input_image_path)
final_path = os.path.join(output_folder, f"{original_name}.{target_format}")
os.rename(temp_path, final_path)
# Add only if conversion is actually performed
if ext[1:].lower() != target_format:
original_extensions.add(ext[1:].upper())
except Exception as e:
print(f"Error during overwrite process for {file}: {e}")
# If user does not want to overwrite original images: convert and save (into the same folder, risking name conflicts)
else:
print("\nWarning: If the target file already exists in this folder, the conversion will be skipped to prevent unexpected overwriting.")
print_divider()
for file in os.listdir(input_folder):
if file.lower().endswith((".jpg", ".jpeg", ".png", ".webp")):
_, ext = os.path.splitext(file)
input_image_path = os.path.join(input_folder, file)
if convert_and_save(input_image_path, output_folder, target_format):
original_extensions.add(ext[1:].upper())
else:
print_divider()
# Make output folder if it does not exist
if not os.path.isdir(output_folder):
os.makedirs(output_folder, exist_ok=True)
for file in os.listdir(input_folder):
if file.lower().endswith((".jpg", ".jpeg", ".png", ".webp")):
_, ext = os.path.splitext(file)
input_image_path = os.path.join(input_folder, file)
if convert_and_save(input_image_path, output_folder, target_format):
original_extensions.add(ext[1:].upper())
unique_extensions = list(original_extensions)
sorted_extensions = sorted(unique_extensions, key = lambda x: sort_order.index(x) if x in sort_order else len(sort_order))
output_extensions_str = ', '.join(sorted_extensions)
print("Successfully Converted!")
print(f"{output_extensions_str.upper()} --> {target_format.upper()}")그리고 저번에 썼던 글에 어떤 분이 vips 써보라고 그게 pillow보다 더 빠르다고 하셨는데..
한국어로 된 문서나 강좌 글 같은게 많이 없어서 그냥 pillow 쓰기로 했습니다.
vips로 만들어보는건 Alpha 버전을 끝내고 서브로 해봐야겠어용
