今天我们就来开发一个基于Python的图形化工具,帮助用户快速统计文件夹中所有图片的详细信息并导出到Excel文件中。
C:\pythoncode\new\image_info_extractor.py
基于实际应用场景,我们的工具需要实现以下核心功能:
经过技术调研,我们选择了以下Python库:
wxPython vs tkinter vs PyQt
openpyxl vs xlwt
Pillow图片处理
class ImageInfoFrame(wx.Frame):
def __init__(self):
super().__init__(None, title="图片文件信息统计", size=(600, 400))
# 创建界面组件
panel = wx.Panel(self)
main_sizer = wx.BoxSizer(wx.VERTICAL)
# 标题、按钮、进度条等组件布局
界面设计采用垂直布局,包含:
def find_image_files(self, folder_path):
"""递归查找所有图片文件"""
image_files = []
image_extensions = {'.jpg', '.jpeg', '.png', '.bmp', '.gif', '.tiff', '.tif', '.webp'}
for root, dirs, files in os.walk(folder_path):
for file in files:
_, ext = os.path.splitext(file.lower())
if ext in image_extensions:
image_files.append(os.path.join(root, file))
return image_files
算法特点:
os.walk()
进行深度优先遍历def get_image_info(self, file_path):
"""提取单个图片文件的完整信息"""
try:
# 文件系统信息
stat = os.stat(file_path)
filename = os.path.basename(file_path)
date = datetime.datetime.fromtimestamp(stat.st_mtime).strftime('%Y-%m-%d %H:%M:%S')
size = stat.st_size
# 图片特有信息
with Image.open(file_path) as img:
width, height = img.size
resolution = f"{width}x{height}"
return {
'filename': filename,
'path': str(file_path),
'date': date,
'size': size,
'resolution': resolution
}
except Exception:
return None
信息提取策略:
os.stat()
获取文件系统元数据def export_to_excel(self, image_info_list, output_path):
"""高效的Excel数据导出"""
workbook = Workbook()
worksheet = workbook.active
worksheet.title = '图片信息'
# 设置表头样式
headers = ['文件名', '完整路径', '修改日期', '文件大小(字节)', '分辨率']
for col, header in enumerate(headers, 1):
cell = worksheet.cell(row=1, column=col, value=header)
cell.font = Font(bold=True)
# 批量写入数据
for row, info in enumerate(image_info_list, 2):
worksheet.cell(row=row, column=1, value=info['filename'])
# ... 其他字段
# 自动调整列宽
worksheet.column_dimensions['A'].width = 25
workbook.save(output_path)
导出优化:
为了防止界面冻结,我们使用了wxPython的CallAfter
机制:
def on_start_scan(self, event):
# UI准备工作
self.scan_btn.Enable(False)
wx.CallAfter(self.process_images, output_path)
def process_images(self, output_path):
# 在后台线程中处理大量文件
for file_path in image_files:
# 处理单个文件
if processed % 10 == 0:
wx.GetApp().Yield() # 让UI保持响应
# 实时更新处理进度
progress = int((processed / total_files) * 100)
self.progress.SetValue(progress)
self.status_text.SetLabel(f"已处理 {processed}/{total_files} 个文件...")
with
语句确保图片文件及时关闭try:
# 主要处理逻辑
with Image.open(file_path) as img:
width, height = img.size
except PIL.UnidentifiedImageError:
# 处理无法识别的图片格式
resolution = "格式不支持"
except PermissionError:
# 处理权限问题
return None
except Exception as e:
# 通用异常处理
return None
try:
# 文件处理逻辑
except Exception as e:
error_msg = f"处理过程中出现错误: {str(e)}"
wx.MessageBox(error_msg, "错误", wx.OK | wx.ICON_ERROR)
某摄影工作室有超过10,000张照片需要整理,使用我们的工具后:
某电商网站需要优化商品图片:
concurrent.futures
提升处理速度# 1. 安装依赖库
pip install wxpython pillow openpyxl
# 2. 下载源代码
# 3. 运行程序
python image_info_extractor.py