from PIL import Image import numpy as np import os def convert_jpg_to_bin(input_file, output_file): print(f"Processing: {input_file}") # 打开已经调整尺寸并转换为 JPEG 的图像 image = Image.open(input_file).convert("RGB") # 转换为 NumPy 数组 img_array = np.array(image, dtype=np.uint16) r = img_array[:, :, 0] g = img_array[:, :, 1] b = img_array[:, :, 2] # 计算 RGB565 格式的值 rgb565 = ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3) # 展平数组并保存为 BIN 文件 rgb565.flatten().tofile(output_file) def prepare_image(input_path, temp_dir, target_width, target_height): """ 先调整图片尺寸,保持原始比例,然后将缩放后的图片粘贴到固定尺寸的画布上, 最终保存为 JPEG 格式,确保输出尺寸为 target_width x target_height。 """ with Image.open(input_path) as img: img = img.convert("RGB") # 按比例缩放,使图片适应目标尺寸,但不会超出目标尺寸 img.thumbnail((target_width, target_height)) # 创建一个新的目标尺寸图像,背景填充黑色(可以根据需要修改背景色) new_img = Image.new("RGB", (target_width, target_height), (0, 0, 0)) # 计算居中粘贴的位置 left = (target_width - img.width) // 2 top = (target_height - img.height) // 2 new_img.paste(img, (left, top)) base_name = os.path.splitext(os.path.basename(input_path))[0] jpg_path = os.path.join(temp_dir, f"{base_name}.jpg") new_img.save(jpg_path, "JPEG") print(f"Converted, resized and padded to JPEG: {jpg_path}") return jpg_path def get_sort_key(filename): base_name = os.path.splitext(filename)[0] try: return int(base_name[:2]) except ValueError: return float('inf') def main(): input_dir = r"C:\Users\10561\Desktop\20250221\tft图片" # 图片目录 temp_dir = os.path.join(input_dir, "temp") # 临时目录 output_dir = os.path.join(input_dir, "bin") # 输出目录 os.makedirs(temp_dir, exist_ok=True) os.makedirs(output_dir, exist_ok=True) target_width, target_height = 800, 480 # 获取所有文件,并按照文件名前两位数字排序 files = sorted( [f for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f))], key=get_sort_key ) for file in files: if file in ["System Volume Information"] or ".bin" in file: continue file_base = os.path.splitext(file)[0] input_path = os.path.join(input_dir, file) # 调整尺寸、填充背景并转换为 JPEG jpg_file = prepare_image(input_path, temp_dir, target_width, target_height) # 生成输出 BIN 文件路径 output_file = os.path.join(output_dir, f"{file_base}.bin") print(f"Output BIN: {output_file}") # 转换为 BIN 文件 convert_jpg_to_bin(jpg_file, output_file) # 如有需要,可清理临时目录 # for temp_file in os.listdir(temp_dir): # os.remove(os.path.join(temp_dir, temp_file)) # os.rmdir(temp_dir) if __name__ == '__main__': main()