86 lines
4.1 KiB
Python
86 lines
4.1 KiB
Python
import os
|
||
import re
|
||
import argparse
|
||
import subprocess
|
||
|
||
def extract_byte_array_from_c_file(file_path):
|
||
"""Извлекает массив байт из C-файла, начиная с '#if LV_COLOR_DEPTH == 32' и заканчивая '#endif', исключая комментарии и строки '#if' и '#endif'."""
|
||
with open(file_path, 'r', encoding='utf-8') as file:
|
||
content = file.read()
|
||
|
||
# Ищем нужный участок текста между '#if LV_COLOR_DEPTH == 32' и '#endif'
|
||
pattern = r'#if LV_COLOR_DEPTH == 32(.*?)#endif'
|
||
match = re.search(pattern, content, re.DOTALL)
|
||
|
||
if match:
|
||
byte_array_content = match.group(1)
|
||
|
||
# Удаляем все комментарии (строки, начинающиеся с /* и заканчивающиеся на */)
|
||
byte_array_content = re.sub(r'/\*.*?\*/', '', byte_array_content, flags=re.DOTALL)
|
||
|
||
# Удаляем саму строку #if LV_COLOR_DEPTH == 32 и #endif
|
||
byte_array_content = byte_array_content.strip()
|
||
|
||
return byte_array_content
|
||
else:
|
||
return None
|
||
|
||
def extract_image_dimensions(file_path):
|
||
"""Извлекает размеры изображения (ширину и высоту) из C-файла."""
|
||
with open(file_path, 'r', encoding='utf-8') as file:
|
||
content = file.read()
|
||
|
||
# Ищем ширину и высоту
|
||
width_pattern = r'\.header\.w\s*=\s*(\d+)'
|
||
height_pattern = r'\.header\.h\s*=\s*(\d+)'
|
||
|
||
width_match = re.search(width_pattern, content)
|
||
height_match = re.search(height_pattern, content)
|
||
|
||
if width_match and height_match:
|
||
width = int(width_match.group(1))
|
||
height = int(height_match.group(1))
|
||
return width, height
|
||
else:
|
||
return None, None
|
||
|
||
def process_directory(directory_path):
|
||
"""Обрабатывает все C-файлы в указанной директории и сохраняет найденные массивы байт в отдельные файлы."""
|
||
for root, dirs, files in os.walk(directory_path):
|
||
for file_name in files:
|
||
if file_name.endswith('.c'):
|
||
file_path = os.path.join(root, file_name)
|
||
|
||
# Извлекаем массив байт
|
||
byte_array = extract_byte_array_from_c_file(file_path)
|
||
|
||
if byte_array:
|
||
# Извлекаем размеры изображения
|
||
width, height = extract_image_dimensions(file_path)
|
||
|
||
if width is not None and height is not None:
|
||
# Создаем новый файл с таким же именем, как у исходного C-файла
|
||
output_file_path = os.path.splitext(file_path)[0] + '_byte_array.txt'
|
||
with open(output_file_path, 'w', encoding='utf-8') as output_file:
|
||
output_file.write(byte_array)
|
||
print(f"Массив байт для файла {file_name} сохранен в {output_file_path}")
|
||
|
||
# Запускаем внешний скрипт для обработки изображения
|
||
subprocess.run(['python', 'make_image_from_file.py', output_file_path, str(width), str(height)])
|
||
else:
|
||
print(f"Не удалось извлечь размеры изображения из файла {file_name}")
|
||
|
||
def main():
|
||
# Создание парсера аргументов
|
||
parser = argparse.ArgumentParser(description="Извлекает массив байт из C-файлов и сохраняет их в отдельные текстовые файлы.")
|
||
parser.add_argument('directory', type=str, help="Путь к директории с C-файлами")
|
||
|
||
# Парсинг аргументов
|
||
args = parser.parse_args()
|
||
|
||
# Обработка указанной директории
|
||
process_directory(args.directory)
|
||
|
||
if __name__ == '__main__':
|
||
main()
|