import os from PIL import Image, ExifTags import io def find_image_path(folder, base_filename): """ 在指定文件夹中查找图片,支持 jpg/jpeg/png 等多种后缀。 :param folder: 文件夹路径 :param base_filename: 基础文件名(不带后缀,例如 "1" 或 "me_image") :return: 找到的完整文件路径,如果没找到则返回 None """ if not os.path.exists(folder): return None # 支持的后缀列表 (包含大小写) extensions = [ ".jpg", ".JPG", ".jpeg", ".JPEG", ".png", ".PNG", ".bmp", ".BMP" ] for ext in extensions: # 拼凑完整路径,例如 data/images/张三/1.png full_path = os.path.join(folder, base_filename + ext) if os.path.exists(full_path): return full_path return None def get_corrected_image_stream(img_path): """ 读取图片,根据 EXIF 信息修正旋转方向,并返回 BytesIO 对象。 这样不需要修改原文件,直接在内存中处理。 """ image = Image.open(img_path) # 获取 EXIF 数据 try: for orientation in ExifTags.TAGS.keys(): if ExifTags.TAGS[orientation] == 'Orientation': break exif = dict(image._getexif().items()) if exif[orientation] == 3: image = image.rotate(180, expand=True) elif exif[orientation] == 6: image = image.rotate(270, expand=True) elif exif[orientation] == 8: image = image.rotate(90, expand=True) except (AttributeError, KeyError, IndexError): # 如果图片没有 EXIF 数据或不需要旋转,则忽略 pass # 将处理后的图片保存到内存流中 image_stream = io.BytesIO() # 注意:保存时保持原格式,如果是 PNG 等无 EXIF 的格式会自动处理 img_format = image.format if image.format else 'JPEG' image.save(image_stream, format=img_format) image_stream.seek(0) # 指针回到开头 return image_stream