[Python] 纯文本查看 复制代码 import os
from PIL import Image
# 假设的DPI值,用于将像素转换为毫米(1英寸 = 25.4毫米)
DPI = 300
PIXELS_TO_MM = 25.4 / DPI
# 定义标准纸张尺寸(这里以A系列为例,单位:毫米)
standard_paper_sizes = {
'A0': (841, 1189),
'A1': (594, 841),
'A2': (420, 594),
'A3': (297, 420),
'A4': (210, 297),
# ... 可以继续添加其他A系列纸张尺寸
}
# 检查图片尺寸并确定最接近的纸张尺寸及方向
def check_image_size_and_orientation(file_path, dpi=DPI):
with Image.open(file_path) as img:
width, height = img.size
# 将像素尺寸转换为毫米
width_mm = width * PIXELS_TO_MM
height_mm = height * PIXELS_TO_MM
min_dim_mm = min(width_mm, height_mm)
aspect_ratio = width / height if width > height else height / width
# 遍历标准纸张尺寸,找到最接近的纸张及方向
closest_size = None
closest_aspect_ratio_diff = float('inf')
orientation = None
for size_name, (std_width_mm, std_height_mm) in standard_paper_sizes.items():
std_aspect_ratio = std_width_mm / std_height_mm
# 计算当前纸张尺寸与图片尺寸的比例
scale = min_dim_mm / min(std_width_mm, std_height_mm)
# 检查比例是否在0.8到1.2之间
if 0.8 <= scale <= 1.2:
# 计算当前纸张宽高比与图片宽高比的差异
aspect_ratio_diff = abs(aspect_ratio - std_aspect_ratio)
# 如果当前差异更小,或者比例相同但之前未找到匹配的纸张,则更新最接近的纸张和宽高比差异
if aspect_ratio_diff < closest_aspect_ratio_diff or (
aspect_ratio_diff == closest_aspect_ratio_diff and closest_size is None):
closest_size = size_name
closest_aspect_ratio_diff = aspect_ratio_diff
# 判断方向(横向或纵向)
orientation = '横向' if aspect_ratio > std_aspect_ratio else '纵向'
return closest_size, orientation
# 遍历文件夹中的图片文件
def check_images_in_folder(folder_path, dpi=DPI):
for filename in os.listdir(folder_path):
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.tiff', '.bmp', '.gif')):
file_path = os.path.join(folder_path, filename)
size, orientation = check_image_size_and_orientation(file_path, dpi)
if size:
print(f"{file_path} 属于 {size} 纸张,方向是 {orientation}。")
else:
print(f"{file_path} 不接近任何标准纸张尺寸。")
# 使用示例
folder_to_check = "d:/a" # 替换为你要检查的文件夹路径
check_images_in_folder(folder_to_check)
|