Select Git revision
png_to_array.py
png_to_array.py 1.01 KiB
from PIL import Image
import numpy as np
def png_to_c_array(png_file_path, output_file_path, array_name):
# Load the image
image = Image.open(png_file_path)
image = image.convert('RGB') # Ensure image is in RGB format
pixel_data = np.array(image)
# Get image dimensions
height, width, _ = pixel_data.shape
# Open the output file
with open(output_file_path, 'w') as f:
# Write the array declaration
f.write(f'static const unsigned char {array_name}[{height}][{width}][3] =\n')
f.write('{\n')
# Write the pixel data
for row in pixel_data:
f.write('\t{')
f.write(','.join(f'{{{r},{g},{b}}}' for r, g, b in row))
f.write('},\n')
# Close the array declaration
f.write('};\n')
# Example usage
png_file_path = 'space_R.png' # Input PNG file path
output_file_path = 'key.txt' # Output text file path
array_name = 'empty_space_r' # C array name
png_to_c_array(png_file_path, output_file_path, array_name)