Files
scripts/lvgl/make_image_from_file.py
2024-12-02 19:38:23 +03:00

67 lines
3.1 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.
import binascii
from PIL import Image
import sys
import os
def extract_bytes(input_file):
# Создаем имя для выходного бинарного файла, используя имя входного
base_name = os.path.splitext(input_file)[0]
output_file = base_name + '_output.bin'
with open(input_file, 'r') as f_in:
data = f_in.read()
# Список для хранения байтов
byte_array = []
# Проходим по строке и извлекаем байты, начинающиеся с '0x'
i = 0
while i < len(data):
if data[i:i+2] == '0x': # Ищем '0x'
hex_str = data[i+2:i+4] # Берем два символа после '0x'
if len(hex_str) == 2: # Убедимся, что это валидный байт
byte_array.append(binascii.unhexlify(hex_str)) # Преобразуем в байт
i += 4 # Пропускаем этот байт
else:
i += 1 # Пропускаем все остальные символы
# Записываем полученные байты в новый файл
with open(output_file, 'wb') as f_out:
f_out.write(b''.join(byte_array))
print(f"Байты записаны в {output_file}")
return output_file # Возвращаем имя бинарного файла
def create_image_from_bytes(byte_file, image_file, width, height):
# Читаем байты из файла
with open(byte_file, 'rb') as f:
byte_data = f.read()
# Переводим данные в список для изменения порядка байтов (R <-> B)
byte_data = bytearray(byte_data)
# Проходим по данным и меняем местами байты для каналов R и B
for i in range(0, len(byte_data), 4): # шаг 4, потому что каждый пиксель 4 байта
# Меняем местами R и B (преобразуем из BGRA в RGBA)
byte_data[i], byte_data[i+2] = byte_data[i+2], byte_data[i]
# Преобразуем байты в изображение
image = Image.frombytes('RGBA', (width, height), bytes(byte_data))
image.save(image_file)
print(f"Изображение сохранено как {image_file}")
if __name__ == "__main__":
input_file = sys.argv[1] # Путь к текстовому файлу
width = int(sys.argv[2]) # Ширина изображения
height = int(sys.argv[3]) # Высота изображения
# Извлекаем байты из текстового файла и записываем в бинарный файл
output_file = extract_bytes(input_file)
# Создаем имя для изображения, используя имя входного файла
base_name = os.path.splitext(input_file)[0]
image_file = base_name + '.png'
# Создаем изображение из бинарных данных
create_image_from_bytes(output_file, image_file, width, height)