Skip to content

Instantly share code, notes, and snippets.

@zeemyself
Created August 13, 2024 16:44
Show Gist options
  • Save zeemyself/02558b09eca94e37ce209dab1af81e0c to your computer and use it in GitHub Desktop.
Save zeemyself/02558b09eca94e37ce209dab1af81e0c to your computer and use it in GitHub Desktop.
PandaTouch image in Python
from PIL import Image
import struct
def process_image(input_file, output_file, max_size=(250, 250)):
# Open the image using PIL
with Image.open(input_file) as img:
# Scale the image down to fit within max_size while maintaining aspect ratio
img.thumbnail(max_size)
# Ensure the image is in RGBA mode
img = img.convert('RGBA')
width, height = img.size
# Prepare the binary content
binary_content = bytearray()
header = bytes.fromhex('DFAD000001F26E65775F70616E64612E706E67000000')
binary_content.extend(header)
# Pack the size as a 4-byte unsigned integer in little endian
size_bytes = struct.pack('<I', width * height * 3 + 4)
binary_content.extend(size_bytes)
dimensions = ((height * 4) << 19) + ((width * 4) << 8) + 5
dimensions_bytes = struct.pack('<I', dimensions)
binary_content.extend(dimensions_bytes)
# Process each pixel row by row
for y in range(height):
for x in range(width):
r, g, b, a = img.getpixel((x, y))
pixel = (a << 16) + ((r >> 3) << 11) + ((g >> 2) << 5) + (b >>3)
pixel_bytes = struct.pack('<I', pixel)[:3]
binary_content.extend(pixel_bytes)
# Write the binary content to the output file
with open(output_file, 'wb') as f:
f.write(binary_content)
@zeemyself
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment