Embedded_game/img2bin.py
2025-01-02 12:48:11 +08:00

103 lines
3.2 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# -*- coding:utf-8 -*-
# @Author len
# @Create 2023/10/26 9:18
from PIL import Image
import numpy as np
import os
def convert_jpg_to_bin(input_file, output_file, max_width, max_height):
# 打开JPEG图像
image = Image.open(input_file)
print(f"Processing: {input_file}")
# 限制图像尺寸
image.thumbnail((max_width, max_height))
# 将图像转换为RGB模式
image = image.convert("RGB")
# 创建一个空白的16位彩色图像
result_image = np.zeros((image.size[1], image.size[0]), dtype=np.uint16)
# 遍历图像的每个像素
for y in range(image.size[1]):
for x in range(image.size[0]):
# 获取RGB值
r, g, b = image.getpixel((x, y))
# 将RGB值转换为RGB565格式
pixel_value = ((r & 0b11111000) << 8) | ((g & 0b11111100) << 3) | (b >> 3)
# 将RGB565值存储到16位彩色图像中
result_image[y, x] = pixel_value
# 将三维数组展平为一维数组
flattened_array = result_image.flatten()
# 保存为BIN文件
with open(output_file, "wb") as file:
file.write(flattened_array.tobytes())
def ensure_jpg_format(input_path, temp_dir):
# 确保文件是JPEG格式如果不是则转换为JPEG
with Image.open(input_path) as img:
if img.format != "JPEG":
base_name = os.path.splitext(os.path.basename(input_path))[0]
jpg_path = os.path.join(temp_dir, f"{base_name}.jpg")
img = img.convert("RGB") # 转换为RGB模式
img.save(jpg_path, "JPEG")
print(f"Converted to JPEG: {jpg_path}")
return jpg_path
return input_path
def get_sort_key(filename):
# 提取文件名前两位数字用于排序
base_name = os.path.splitext(filename)[0]
try:
# 尝试将前两位数字转换为整数
return int(base_name[:2])
except ValueError:
# 如果无法转换为数字,则返回一个较大的默认值
return float('inf')
# 使用示例
input_file = r"C:\Users\10561\Desktop\002\任务2" # 图片地址
temp_dir = os.path.join(input_file, "temp") # 临时目录
output_dir = os.path.join(input_file, "bin") # 输出目录
os.makedirs(temp_dir, exist_ok=True) # 创建临时目录
os.makedirs(output_dir, exist_ok=True) # 创建输出目录
max_width = 800
max_height = 480
# 获取文件列表并忽略目录,同时按照前两位数字排序
files = sorted(
[file for file in os.listdir(input_file) if os.path.isfile(os.path.join(input_file, file))],
key=get_sort_key
)
for file in files:
print(file)
if file in ["System Volume Information"] or ".bin" in file:
continue
portion = os.path.splitext(file)
input001 = os.path.join(input_file, file)
# 确保输入文件是JPEG格式
jpg_file = ensure_jpg_format(input001, temp_dir)
# 生成输出文件路径
out001 = os.path.join(output_dir, f"{portion[0]}.bin")
print(f"Output BIN: {out001}")
# 转换为BIN文件
convert_jpg_to_bin(jpg_file, out001, max_width, max_height)
# 清理临时目录
for temp_file in os.listdir(temp_dir):
os.remove(os.path.join(temp_dir, temp_file))
os.rmdir(temp_dir)