秀人网图片随机优化
This commit is contained in:
@@ -3,24 +3,17 @@ import random
|
|||||||
|
|
||||||
|
|
||||||
def get_random_file_from_dir(directory):
|
def get_random_file_from_dir(directory):
|
||||||
selected_file = None
|
|
||||||
file_count = 0
|
|
||||||
# 定义图片文件的扩展名列表
|
|
||||||
image_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.webp'}
|
image_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.webp'}
|
||||||
|
image_files = []
|
||||||
|
|
||||||
# 遍历目录及其所有子目录
|
with os.scandir(directory) as entries:
|
||||||
for root, dirs, files in os.walk(directory):
|
for entry in entries:
|
||||||
for file in files:
|
if entry.is_file():
|
||||||
# 获取文件扩展名
|
_, ext = os.path.splitext(entry.name)
|
||||||
_, ext = os.path.splitext(file)
|
if ext.lower() in image_extensions:
|
||||||
# 只考虑图片文件
|
image_files.append(entry.path)
|
||||||
if ext.lower() in image_extensions:
|
|
||||||
file_count += 1
|
|
||||||
if random.randint(1, file_count) == 1:
|
|
||||||
# 每个图片文件有1/file_count的概率被选中
|
|
||||||
selected_file = os.path.join(root, file)
|
|
||||||
|
|
||||||
return selected_file
|
return random.choice(image_files) if image_files else None
|
||||||
|
|
||||||
|
|
||||||
def get_xiuren_pic():
|
def get_xiuren_pic():
|
||||||
|
|||||||
Reference in New Issue
Block a user