用Python编写一个脚本来实现以下功能:扫描图像文件中的水印日期,将所有具有相同日期的图片归类并存入一个新的子文件夹?并且,新文件夹的命名应该基于这些图片的日期。
时间: 2024-11-22 18:35:21 浏览: 25
要编写一个Python脚本来实现这一功能,我们可以使用PIL(Python Imaging Library)库来读取图像文件,然后解析图像中的日期。下面是一个简单的示例,假设我们有一个名为`images`的目录,其中包含嵌有水印日期的图片:
```python
from PIL import Image
import os
# 定义要搜索的日期模式
date_pattern = r'\d{4}\d{2}\d{2}' # 匹配形如 "YYYYMMDD" 的日期
def find_watermark_dates(image_path):
with Image.open(image_path) as img:
try:
text = img.info.get('Comments') or img.info.get('Author')
if text and date_pattern.match(text): # 如果存在文本信息且匹配日期模式
return text
except Exception as e:
print(f"Error parsing {image_path}: {e}")
return None
# 获取images目录下的所有图像文件
image_dir = 'images'
watermarked_images = []
for filename in os.listdir(image_dir):
if filename.endswith(('.jpg', '.jpeg', '.png')):
file_path = os.path.join(image_dir, filename)
watermark_date = find_watermark_dates(file_path)
if watermark_date:
watermarked_images.append((file_path, watermark_date))
# 对于每个日期,创建一个子目录并将图片移动到该目录
unique_dates = set(watermark_date for _, watermark_date in watermarked_images)
for date in unique_dates:
date_folder = f"{date[:4]}_{date[4:6]}_{date[6:]}" # 格式化日期作为子文件夹名
if not os.path.exists(date_folder):
os.makedirs(date_folder)
images_for_date = [img_path for img_path, _ in watermarked_images if _ == date]
for img_path in images_for_date:
new_img_path = os.path.join(date_folder, os.path.basename(img_path))
os.rename(img_path, new_img_path)
# 结果说明:现在所有匹配日期的图片已按日期分类存储在各自的子文件夹中。
阅读全文