Last active
April 12, 2025 10:19
-
-
Save ivon852/7cfa3e3e4f56ee8d52eec1124d9be028 to your computer and use it in GitHub Desktop.
Termux Android手機照片批次加上EXIF日期Python程式
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""" | |
如何使用這個程式: | |
1. 安裝Termux APP https://f-droid.org/zh_Hant/packages/com.termux/ | |
2. 允許存取手機內部儲存空間:termux-setup-storage | |
3. 安裝Python套件:pkg install python3 python-pip | |
4. 安裝Pillow:pkg install python-pillow | |
5. 將照片放在手機內部儲存空間/DCIM/Camera/,然後處理後的照片會輸出到手機內部儲存空間/DCIM/output/ | |
6. 執行:python3 main.py | |
""" | |
from PIL import Image, ImageDraw, ImageFont, ExifTags | |
import os | |
input_dir = './storage/shared/DCIM/Camera/' | |
output_dir = './storage/shared/DCIM/output/' | |
os.makedirs(output_dir, exist_ok=True) | |
# 字型路徑 | |
font_path = "/data/data/com.termux/files/usr/share/fonts/TTF/DejaVuSans-Bold.ttf" | |
font_size = 96 | |
try: | |
font = ImageFont.truetype(font_path, font_size) | |
except OSError: | |
print("無法載入字體,請確認字體路徑正確") | |
exit(1) | |
# 遍歷資料夾中的所有照片 | |
for filename in os.listdir(input_dir): | |
if filename.lower().endswith(('.jpg', '.jpeg', '.png')): | |
img_path = os.path.join(input_dir, filename) | |
image = Image.open(img_path) | |
# 確保轉成 RGB 模式 | |
if image.mode != 'RGB': | |
image = image.convert('RGB') | |
draw = ImageDraw.Draw(image) | |
# 嘗試讀取 EXIF | |
exif_text = "" | |
try: | |
exif_data = image._getexif() | |
if exif_data: | |
exif = { | |
ExifTags.TAGS.get(k, k): v | |
for k, v in exif_data.items() | |
if k in ExifTags.TAGS | |
} | |
datetime = exif.get("DateTimeOriginal") or exif.get("DateTime") | |
model = exif.get("Model") | |
exif_text = f"{model or ''} {datetime or ''}".strip() | |
except Exception as e: | |
print(f"讀取 EXIF 發生錯誤:{e}") | |
if exif_text: | |
# 計算文字邊界 | |
bbox = draw.textbbox((0, 0), exif_text, font=font) | |
text_width = bbox[2] - bbox[0] | |
text_height = bbox[3] - bbox[1] | |
# 設定右下角的位置 | |
margin = 100 | |
x = image.width - text_width - margin | |
y = image.height - text_height - margin | |
# 畫陰影(黑) | |
draw.text((x + 2, y + 2), exif_text, font=font, fill=(0, 0, 0)) | |
# 畫主文字(白) | |
draw.text((x, y), exif_text, font=font, fill=(255, 255, 255)) | |
else: | |
print(f"{filename} 沒有 EXIF 或未能擷取到資訊") | |
# 儲存輸出照片 | |
output_path = os.path.join(output_dir, filename) | |
image.save(output_path) | |
print("所有照片處理完成!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment