81 lines
2.4 KiB
Python
Executable File
81 lines
2.4 KiB
Python
Executable File
import os
|
||
import hashlib
|
||
from PIL import Image
|
||
import mysql.connector
|
||
from math import ceil
|
||
from tqdm import tqdm
|
||
|
||
# 数据库连接配置
|
||
db_config = {
|
||
'host': '192.168.1.193',
|
||
'user': 'meiapi',
|
||
'password': '',
|
||
'database': 'meiapi'
|
||
}
|
||
|
||
# 获取数据库连接
|
||
def get_db_connection():
|
||
return mysql.connector.connect(**db_config)
|
||
|
||
# 生成短哈希
|
||
def generate_short_hash(filename, length=8):
|
||
hash_object = hashlib.sha256(filename.encode())
|
||
hex_dig = hash_object.hexdigest()
|
||
return hex_dig[:length]
|
||
|
||
# 压缩图像(转换为WebP格式)
|
||
def compress_image(input_path, output_path):
|
||
with Image.open(input_path) as img:
|
||
img.save(output_path, "WEBP")
|
||
|
||
# 批量处理图像
|
||
def batch_process_images(source_dir, target_dir, theme, et):
|
||
# 确保目标目录存在
|
||
if not os.path.exists(target_dir):
|
||
os.makedirs(target_dir)
|
||
|
||
# 获取数据库连接
|
||
conn = get_db_connection()
|
||
cursor = conn.cursor()
|
||
|
||
# 获取源目录中的所有文件列表
|
||
files = [f for f in os.listdir(source_dir) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.webp', '.ico'))]
|
||
|
||
# 使用tqdm包装文件列表,以显示进度条
|
||
for filename in tqdm(files, desc="Processing images", unit="file"):
|
||
file_path = os.path.join(source_dir, filename)
|
||
file_extension = os.path.splitext(filename)[1].lower()
|
||
|
||
# 生成短哈希
|
||
short_hash = generate_short_hash(filename)
|
||
new_filename = f"{short_hash}{file_extension}"
|
||
new_file_path = os.path.join(target_dir, new_filename)
|
||
|
||
# 重命名并移动文件
|
||
os.rename(file_path, new_file_path)
|
||
|
||
# 压缩图像
|
||
webp_filename = f"{short_hash}.webp"
|
||
webp_file_path = os.path.join(target_dir, webp_filename)
|
||
compress_image(new_file_path, webp_file_path)
|
||
|
||
# 插入数据库
|
||
insert_query = "INSERT INTO images (filename, theme, et, webp_path) VALUES (%s, %s, %s, %s)"
|
||
cursor.execute(insert_query, (new_filename, theme, et, webp_filename))
|
||
conn.commit()
|
||
|
||
# 关闭数据库连接
|
||
cursor.close()
|
||
conn.close()
|
||
|
||
if __name__ == '__main__':
|
||
# 指定源目录和目标目录
|
||
source_directory = 'catch/'
|
||
target_directory = 'img/'
|
||
|
||
# 指定theme和et字段
|
||
theme = 'fox' # 可以改为其他主题
|
||
et = 'all' # 可以改为其他设备类型
|
||
|
||
# 执行批量处理
|
||
batch_process_images(source_directory, target_directory, theme, et) |