~/Building a Custom Image Format in Python

Jan 20, 2019


Design your own image format by defining a simple structure for the file. You can use struct for binary data handling. Below is an example for a format that stores width, height, and raw RGB pixel values.

File structure example:

Write an image:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import struct

width = 2
height = 2
pixels = [
    255, 0, 0,      # Red
    0, 255, 0,      # Green
    0, 0, 255,      # Blue
    255, 255, 0     # Yellow
]

with open("custom.img", "wb") as f:
    f.write(struct.pack("II", width, height))
    f.write(bytearray(pixels))

Read the image:

1
2
3
4
5
6
import struct

with open("custom.img", "rb") as f:
    width, height = struct.unpack("II", f.read(8))
    pixel_data = f.read(width * height * 3)
    print(list(pixel_data))

This format is raw and lacks features like compression or metadata. To extend, add headers, compression (see zlib), or more color channels as needed.

Always document your structure so others can interpret your images.

Tags: [python] [image] [format]