Chào mọi người,
Dạo này mình có nhu cầu xử lý một lượng lớn ảnh chụp từ điện thoại, và nhận ra việc sắp xếp, đặt tên theo ngày tháng chụp là rất mất thời gian. Mình tìm hiểu và phát hiện ra Python có thể giải quyết ngon lành vụ này. Hôm nay chia sẻ lại cho anh em nào đang gặp tình huống tương tự.
Vấn đề: Ảnh chụp không theo thứ tự, tên file mặc định khó quản lý, cần sắp xếp vào thư mục theo ngày và đặt tên lại cho dễ nhìn.
Giải pháp: Sử dụng Python để đọc thông tin ngày tháng từ metadata (EXIF) của ảnh, sau đó di chuyển và đổi tên file.
Yêu cầu:
- Cài đặt Python.
- Cài đặt thư viện Pillow:
pip install Pillow
Code tham khảo:
from PIL import Image
import os
import shutil
SOURCE_DIR = 'path/to/your/photos'
DEST_DIR = 'path/to/organized/photos'
def organize_photos(source_folder, destination_folder):
if not os.path.exists(destination_folder):
os.makedirs(destination_folder)
for filename in os.listdir(source_folder):
if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
filepath = os.path.join(source_folder, filename)
try:
with Image.open(filepath) as img:
exif_data = img._getexif()
if exif_data:
# EXIF tag for DateTimeOriginal is 36867
date_taken_str = exif_data.get(36867)
if date_taken_str:
# Format: 'YYYY:MM:DD HH:MM:SS'
date_obj = datetime.strptime(date_taken_str, '%Y:%m:%d %H:%M:%S')
year = date_obj.strftime('%Y')
month = date_obj.strftime('%m')
day = date_obj.strftime('%d')
# Create destination folder structure YYYY/MM/DD
target_dir = os.path.join(destination_folder, year, month, day)
if not os.path.exists(target_dir):
os.makedirs(target_dir)
# New filename: YYYYMMDD_HHMMSS_original_name.ext
time_part = date_obj.strftime('%H%M%S')
base_name, ext = os.path.splitext(filename)
new_filename = f'{year}{month}{day}_{time_part}_{base_name}{ext}'
shutil.move(filepath, os.path.join(target_dir, new_filename))
print(f'Moved: {filename} -> {os.path.join(target_dir, new_filename)}')
else:
print(f'Skipped: No date taken info for {filename}')
else:
print(f'Skipped: No EXIF data for {filename}')
except Exception as e:
print(f'Error processing {filename}: {e}')
# Replace with your actual paths
organize_photos(SOURCE_DIR, DEST_DIR)
Lưu ý:
- Bạn cần thay
'path/to/your/photos'và'path/to/organized/photos'bằng đường dẫn thực tế trên máy của bạn. - Code này chỉ lấy ngày giờ chụp từ metadata. Một số ảnh cũ hoặc ảnh scan có thể không có thông tin này.
- Nên sao lưu ảnh gốc trước khi chạy script để tránh mất dữ liệu không mong muốn.
Hy vọng mẹo nhỏ này giúp ích cho anh em nào đang cần quản lý kho ảnh của mình hiệu quả hơn. Có gì thắc mắc cứ hỏi nhé!