Open and inspect
An image file is two things: a header that says how big the picture is, and the pixels. libstb lets you read the header alone, which costs almost nothing and allocates no pixel memory, and then decode only what you want, in the shape you want.
import os
import libstb as stb
os.makedirs("out", exist_ok=True)
# The header alone: the size and the channels, with no pixel decoded.
for name in ("camera.png", "astronaut.png", "badge.png", "rocket.jpg"):
info = stb.iminfo(name)
print(f"{name}: {info.width}x{info.height}, {info.channels} channel(s)")
img = stb.Image.open("astronaut.png")
print("red of the pixel (0, 0):", img.tobytes()[0])
# Ask for another channel count while decoding.
gray = stb.Image.open("astronaut.png", format=stb.PixelFormat.GRAY)
rgba = stb.Image.open("astronaut.png", format=stb.PixelFormat.RGBA)
print(f"gray has {gray.channels}, rgba has {rgba.channels}")
# Or turn it over while decoding.
flipped = stb.Image.open("astronaut.png", flip=True)
gray.write("out/gray.png")
flipped.write("out/flipped.png")
camera.png: 512x512, 1 channel(s)
astronaut.png: 512x512, 3 channel(s)
badge.png: 160x160, 4 channel(s)
rocket.jpg: 640x427, 3 channel(s)
red of the pixel (0, 0): 154
gray has 1, rgba has 4


The header
stb.iminfo(source) takes a path or the bytes of a file and returns the width, the height, the channel count, the pixel format and the EXIF orientation.
This is how you decide, before decoding, whether a file is one you are willing to open: see untrusted input.
Channels
A picture has 1 (gray), 2 (gray and alpha), 3 (RGB) or 4 (RGBA) channels, and the file decides which. Decoding can ask for another count: a color picture asked for as gray comes back gray, and a picture without alpha asked for as RGBA gets an opaque alpha. To change an image you already have, use convert, on the channels and alpha page.
Flip and EXIF
Decoding can also flip the picture vertically, and can turn a phone photo upright using its EXIF tag. The tag has its own page: EXIF orientation.
API at a glance
| Header only | stb.iminfo(path_or_bytes) |
|---|---|
| Open a file | stb.Image.open(path, format=..., flip=...) |
| Open from memory | stb.Image.decode(data) |
| Channel count | format=stb.PixelFormat.GRAY (or GRAY_ALPHA, RGB, RGBA) |
| Flip while decoding | flip=True |
| One byte of the pixels | img.tobytes()[i] |