Skip to main content

coloX Img Image Module Lua Programming Guide

The coloX image module supports loading PNG/JPG/GIF/WebP images, drawing (tiling/cropping/rotation/scaling), and GIF/WebP animation playback.

Enabling the Module​

The image module is ready to use: img_* globals are registered at cartridge startup, without usemod.


Contents​

  1. Core concepts
  2. Image loading
  3. Image drawing
  4. GIF animation
  5. WebP animation
  6. Incoming image streams: airimg
  7. Complete API index

1. Core Concepts​

Image Objects (img)​

All loading functions return an image object (userdata) holding pixels and associated resources. Call img_close() when finished, or let GC reclaim it automatically.

opflag Drawing Flags​

The opflag parameter controls drawing anchors and blending:

BitDescription
bit01 = Alpha blending (effective only for 32-bit source images with an Alpha channel)
bit1-2X anchor: 0=left, 1=right, 2=center
bit3-4Y anchor: 0=top, 1=bottom, 2=center
local FLAG_ALPHA = 0x01
local FLAG_CENTER_X = 0x04 -- bit2=1, so (flag>>1)&3 == 2
local FLAG_CENTER_Y = 0x10 -- bit4=1, so (flag>>3)&3 == 2

-- Draw centered with alpha blending
img_draw(png, 120, 120, FLAG_ALPHA + FLAG_CENTER_X + FLAG_CENTER_Y)

bpp Color Depth​

Specify the target color depth with bpp when loading. Omitting it or passing nil uses the current platform specification's color depth.

bppFormatDescription
11-bitMonochrome
44-bit16-color palette
88-bit256-color palette
16RGB565High color
32RGBA8888True color + Alpha

Note: WebP supports only bpp=16 or bpp=32.


2. Image Loading​

img_load(picdata [, bpp [, flag [, gifall]]]) → img​

Loads image data (PNG/JPG/GIF/WebP; WebP requires bpp=16/32).

Parameters:

ParameterTypeDefaultDescription
picdatastringRequiredBinary image data (usually embedded with #blob)
bppnumberPlatform defaultTarget color depth (1/4/8/16/32)
flagnumber1 (premultiplied)Image property flags
gifallbooleanfalsetrue = load all GIF frames (stack vertically into one image)

Returns: Image object, or nil on failure.

-- Basic loading
local img = img_load(picdata)

-- Specify 32-bit color depth
local img = img_load(picdata, 32)

-- Load all GIF frames (stacked into one large image)
local gif = img_load(gifdata, nil, nil, true)

Multiframe GIF: With gifall=true, all frames are stacked vertically into one large image (same width; height = frame height × frame count). Loading all frames consumes substantial memory; avoid it where possible.

img_loadwebp(picdata [, bpp [, flag [, opt, cx, cy, cw, ch, sw, sh]]]) → img, fullwidth, fullheight​

Loads a WebP image, supporting cropping and downscaling.

Parameters:

ParameterTypeDefaultDescription
picdatastringRequiredBinary WebP data
bppnumberPlatform defaultTarget color depth (16 or 32 only)
flagnumber1 (premultiplied)Image property flags
optnumber0Options: bit0=load cropped region, bit1=downscale
cx, cy, cw, chnumber0,0,0,0Cropping region
sw, shnumber0,0Downscaled width and height

Returns: img, fullwidth, fullheight (image object + original dimensions).

-- Basic loading
local img, ow, oh = img_loadwebp(webpdata)

-- Crop and downscale while loading
local img, ow, oh = img_loadwebp(webpdata, 16, nil, 0x03, 100, 100, 200, 200, 100, 100)
-- opt=0x03: bit0=crop, bit1=downscale
-- Downscale cropped region (100,100)-(300,300) to (100,100)

img_loadscr(src, sx, sy, sw, sh [, flag]) → img​

Wraps a subregion of screen VRAM or a sprite bank as an img object (zero-copy reference to VM memory).

ParameterTypeDefaultDescription
srcstringRequired"SCR" = screen VRAM; "SPR" = sprite bank
sx, syintegerRequiredRegion top-left coordinates (negative/out-of-range values return nil, without clipping)
sw, shintegerRequiredRegion dimensions; clipped when exceeding the source; <= 0 returns nil
flagnumber0Image property flags (e.g. 1=premultiplied)

The returned img borrows VM memory: ptr points directly to VRAM/SPR, so img_close/GC does not free that memory; contents change live with the screen/sprites. bpp and geometry follow the current spec (as with SCR/SPR in blit). Draw with img_draw*, or pass to vg_load_picture_img to create a ThorVG paint.

-- Capture the top-left 64×64 screen region
local scr = img_loadscr("SCR", 0, 0, 64, 64)
img_draw(scr, 100, 100)

-- Capture a sprite from a sprite bank (assuming tilesize=16)
local spr = img_loadscr("SPR", 0, 0, 16, 16)

img_close(img)​

Releases image resources immediately. Also called automatically by GC.

img_close(img)
img = nil

img_info(img) → w, h, bpp, flag [, frame_h, delays]​

Gets image information.

Returns:

ReturnTypeDescription
w, hnumberImage dimensions
bppnumberBits per pixel
flagnumberImage property flags
frame_hnumberGIF frame height (multiframe GIF images only)
delaystablePer-frame GIF delays in milliseconds (multiframe GIF images only)
local w, h, bpp, flag = img_info(img)
print(string.format("size: %dx%d, bpp: %d", w, h, bpp))

-- GIF information
local w, h, bpp, flag, frame_h, delays = img_info(gif)
print(string.format("gif: %dx%d, frame_h: %d, frames: %d",
w, h, frame_h, #delays))

img_set_flag(img, op, flag) → flag​

Sets image property flags and returns the current flag value.

Parameters:

ParameterTypeDescription
imgimgImage object
opstringOperation: '+'=add flags, '-'=remove flags, '='=set directly
flagnumberProperty flag value (numeric combinations supported)

Common flag values: 0=no special properties, 1=premultiplied Alpha, 4=opaque (skip alpha blending), 8=skip clearing when drawing (may improve performance).

-- Add the opaque flag (disable alpha blending)
img_set_flag(img, '+', 4)

-- Remove the premultiplied-alpha flag
img_set_flag(img, '-', 1)

-- Set flag directly to 0 (clear all flags)
img_set_flag(img, '=', 0)

-- Set and retrieve the current flag
local flag = img_set_flag(img, '=', 5)

3. Image Drawing​

img_draw(img, x, y [, opflag])​

Pastes an image at a screen position.

Parameters:

ParameterTypeDescription
imgimgImage object
x, ynumberDestination position (affected by opflag anchors)
opflagnumberDrawing flags (see core concepts)
-- Draw aligned to the top-left corner
img_draw(img, 10, 20)

-- Draw centered
img_draw(img, 120, 120, 0x01 + 0x04 + 0x10)
-- 0x01=alpha, 0x04=center_x, 0x10=center_y

img_drawex(img, x, y [, opflag, sx, sy, sw, sh])​

Pastes a specified image region onto the screen.

Parameters:

ParameterTypeDefaultDescription
imgimgRequiredImage object
x, ynumberRequiredDestination position
opflagnumber0Drawing flags
sx, synumber0, 0Source region top-left
sw, shnumberImage dimensionsSource region size
-- Draw the top-left 50×50 image region
img_drawex(img, 50, 50, 0, 0, 0, 50, 50)

-- Draw the right half of the image
local w = img_info(img)
img_drawex(img, 0, 0, 0, w / 2, 0, w / 2)

img_drawrot(img, dx, dy, opflag [, sx, sy, sw, sh, angle, zoomx, zoomy])​

Draws an image with rotation and scaling.

Parameters:

ParameterTypeDefaultDescription
imgimgRequiredImage object
dx, dynumberRequiredDestination position
opflagnumber0Drawing flags (reserved parameter, currently ignored)
sx, synumber0, 0Source region top-left
sw, shnumberImage dimensionsSource region size (not drawn if outside image bounds)
anglenumber0Rotation angle (degrees)
zoomxnumber1.0X scale
zoomynumber1.0Y scale
-- Draw rotated by 45 degrees
img_drawrot(img, 120, 120, 1, 0, 0, 80, 80, 45)

-- Downscale to 50%
img_drawrot(img, 120, 120, 1, nil, nil, nil, nil, 0, 0.5, 0.5)

Note: Different source/canvas bpp values are converted automatically (16↔32, palette-based 8bpp→16/32); 4/1bpp sources and unsupported combinations are not drawn. Source regions extending beyond image bounds are not drawn.

img_drawzoom(img, dx, dy, dw, dh [, sx, sy, sw, sh, opflag])​

Scales an image to the specified destination size.

Parameters:

ParameterTypeDefaultDescription
imgimgRequiredImage object
dx, dynumberRequiredDestination position
dw, dhnumberRequiredDestination dimensions
sx, synumber0, 0Source region top-left
sw, shnumberImage dimensionsSource region size
opflagnumber0Drawing flags

opflag bit definitions:

BitDescription
bit81 = Mirror along X
bit91 = Mirror along Y

Nothing is drawn if the source region extends beyond image bounds.

-- Scale the image to 60×60
img_drawzoom(img, 10, 10, 60, 60)

-- Scale and mirror horizontally
img_drawzoom(img, 10, 10, 60, 60, nil, nil, nil, nil, 0x101)

4. GIF Animation​

coloX provides two GIF playback modes:

Mode A: Load All Frames (img_load + img_drawgif)​

Load all frames with img_load (stacked into a large image), then draw by frame index with img_drawgif.

Use when: GIFs are small with few frames and random frame access is needed.

local gifdata =
#blob anim.gif

local gif = img_load(gifdata, nil, nil, true) -- gifall=true

local w, h, bpp, flag, frame_h, delays = img_info(gif)

local frmidx = 1
local delay = 0

function _draw()
cls(dark_green)
local _frmidx, _delay = img_drawgif(gif, frmidx, 0, 0)
print(string.format("%d,%d,%d", frmidx, _frmidx, _delay), 0, 0, red, 0, 16)

delay = delay + 1000 / 30 -- Accumulate each frame (assuming 30fps)
if delay > _delay then
frmidx = _frmidx + 1 -- Advance to the next frame
delay = delay - _delay
end
end

img_drawgif(img, frameidx, x, y [, opflag, sx, sy, sw, sh]) → next_frameidx, delay_ms​

Draws a specified GIF frame.

Parameters:

ParameterTypeDescription
imgimgGIF image object (loaded with gifall=true)
frameidxnumberFrame number (1-based, automatically wraps)
x, ynumberDestination position
opflagnumberDrawing flags
sx, sy, sw, shnumberSource cropping region

Returns:

ReturnDescription
next_frameidxFrame actually drawn (out-of-range input wraps to [1, n])
delay_msCurrent frame delay (milliseconds)

Mode B: Streaming Decoding (img_gif_load / img_gif_file + img_gif_next)​

Decodes GIF frames dynamically and renders as needed to save memory.

Use when: GIFs are large or have many frames, or memory is limited.

img_gif_load(picdata [, bpp]) → img​

Loads a GIF animation from memory for streaming decoding.

local gifdata =
#blob anim.gif
local gif = img_gif_load(gifdata)

img_gif_file(filename [, bpp]) → img​

Loads a GIF animation from a file for streaming decoding.

local gif = img_gif_file("anim.gif")

img_gif_next(img [, force]) → has_next, delay_ms​

Decodes the next frame.

Parameters:

ParameterTypeDefaultDescription
imgimgRequiredGIF image object
forcebooleanfalsetrue = force decoding the next frame (ignore timing)

Returns:

ReturnDescription
has_next0 = last frame; 1 = more frames remain
delay_msCurrent frame delay (milliseconds)

When has_next=0, playback loops automatically according to the GIF loop settings. Use force=true to advance forcibly.

local gifdata =
#blob anim.gif
local gif = img_gif_load(gifdata)

function _draw()
cls(dark_green)
img_gif_next(gif)
img_draw(gif, 0, 0)
end

5. WebP Animation​

WebP animations use streaming decoding, rendering frames as needed to save memory.

img_webpani_load(picdata [, bpp [, flag]]) → img, frame_count​

Loads a WebP animation from memory.

Parameters:

ParameterTypeDefaultDescription
picdatastringRequiredBinary WebP animation data
bppnumberPlatform defaultTarget color depth (validated only; currently does not affect output—the decoding canvas is always 32bpp)
flagnumber0x04 (opaque)Image property flags

Returns: img, frame_count, or nil on failure.

img_webpani_next(img [, force]) → has_next, delay_ms​

Decodes the next WebP animation frame.

Parameters and return values: Same as img_gif_next.

img_webpani_reset(img)​

Resets WebP animation to the first frame.

local webpdata =
#blob anim.webp
local webp, frames = img_webpani_load(webpdata, 32)

function _draw()
cls()
local has_next, delay = img_webpani_next(webp)
img_draw(webp, 0, 0)

if has_next == 0 then
-- Playback has finished; optionally reset
-- img_webpani_reset(webp)
end
end

6. Incoming Image Streams: airimg​

Platform firmware can continuously receive external JPG frames in the background, retaining the latest 2 complete frames. Cartridges pull and render them on demand—frames never appear automatically; cartridges explicitly control all presentation.

For USB device identification, streaming from a computer (including a Python example), and automatic display on the animated home screen without a cartridge, see airimg.md.

Availability: Only firmware with an incoming-frame provider (such as ColoPLAY/knob) supports it. On other platforms (including desktop host emulators), these three functions are unregistered and evaluate to nil (direct calls error); detect support with if img_scrair then ... end. The airdata_* functions similarly depend on a firmware data-channel provider and yield nil or false when unavailable.

img_airinfo() → w, h, frame_id, jpg_len, age_ms | nil​

Inspects metadata for the latest frame with no decoding, at minimal cost; suitable for polling in _update/_draw. The sender increments frame_id (with wrapping); a changed value indicates a new frame. The frame remains available after the call. Returns nil if none is available.

Detecting a stopped stream: Received frames stay in the ring buffer, so this function still returns the last frame after transmission stops. Use age_ms (milliseconds since that frame finished arriving on the device, recalculated on every call) to determine whether the sender is still active. Treat the stream as stopped when age_ms exceeds a threshold larger than the maximum sending interval, e.g. 2000. Cable disconnection, stopped transmission, and wake from sleep are equivalent in terms of age.

img_loadair([bpp [, flag]]) → img | nil​

Decodes the latest frame into an owned image object (same ownership as img_load, released by img_close()/GC). bpp defaults to the current spec's color depth. Returns nil if no frame is available or decoding fails.

local im = img_loadair(16)
if im then
img_draw(im, 0, 0)
img_close(im)
end

img_scrair([x [, y [, flag]]]) → boolean​

Decodes the latest frame directly into screen VRAM. x/y/flag anchor semantics match img_draw, centered by default (flag 0x14). bpp follows the spec (always decoded at spec color depth, naturally matching the screen). No scaling: oversized frames fall back to a centered cropping blit. Returns true on success.

Usage: Optimized for frequent calls; you may call it unconditionally every frame, without caching or deduplicating frames. Repeatedly drawing the same frame is inexpensive. Other drawing may cover it during the frame; the next call restores it automatically.

img_scrair()          -- Decode into the center of the screen
img_scrair(0, 0, 0) -- Align to the top-left corner

Typical Usage: Redraw Only When the Frame Changes​

local last_id = -1
function _draw()
local w, h, id, sz, age = img_airinfo()
if not w then
drawTxt_h("no air frame", 8, 8, 6)
return
end
if id ~= last_id then
last_id = id
img_scrair() -- Decode and display
end
end

Performance: Decoding runs synchronously on the calling thread. Firmware with hardware JPEG decoding takes approximately 10–30ms per frame; software-only decoding of 480x480 takes approximately 150–500ms, suitable for infrequent pulls rather than full-frame-rate video.

Data Channel airdata_* (CXUS v2, Firmware Support Required)​

Airimg's USB interface can also carry bidirectional application data (wire types 16–31). The platform does not interpret the payload. The device has two receive and two send priority queues (prio 0 for normal, 1 for high). A full queue drops its own oldest message. For incoming messages, bit 0 of the sender's header flags selects the queue. The predefined channels are 16=AUDIO (Opus) and 17=INPUT (unified input protocol). Types 18–31 are available to applications. See airimg.md for the protocol and host integration.

airdata_get([prio]) → data, type, tag, sub, seq, remaining | nil​

Removes the oldest message from the selected receive queue (prio defaults to 0). The payload is returned as a binary-safe Lua string. An empty payload returns "", while an empty queue returns nil. type is the channel number, and tag and sub carry application metadata (the header's w/h fields). seq strictly increases within a queue, so gaps indicate drops. remaining is the number of messages left in the queue.

airdata_send(type, data [, prio [, tag [, sub]]]) → boolean​

Adds a message to the send queue. Dropping the oldest message when full still counts as success. Returns false only for invalid arguments or a disconnected USB channel, which can be checked with airdata_ready(). The firmware sets the per-message limit (8 KB by default on knob).

airdata_depth(dir [, prio]) → count, max_count, bytes, max_bytes, dropped | nil​

Queries the queue for dir ("rx" or "tx"). dropped counts all messages discarded because the queue was full. Use it to throttle the sender. On the host, the analogous statistics are in PONG.

airdata_clear(dir) → cleared; airdata_ready() → boolean​

airdata_clear empties the selected queues ("rx", "tx", or "all") and returns the number of messages removed. airdata_ready() checks whether the USB vendor channel is connected.

-- Receive loop: drain the high-priority queue before the normal queue
for prio = 1, 0, -1 do
local d, ty, tag, sub = airdata_get(prio)
if d then --[[ Dispatch by ty ... ]] end
end

7. Complete API Index​

Image Loading​

FunctionReturnsDescription
img_load(picdata [, bpp [, flag [, gifall]]])imgLoad PNG/JPG/GIF/WebP images
img_loadscr(src, sx, sy, sw, sh [, flag])imgCapture a screen VRAM ("SCR")/sprite ("SPR") subregion (zero-copy)
img_loadwebp(picdata [, bpp [, flag [, opt, cx, cy, cw, ch, sw, sh]]])img, w, hLoad WebP images (cropping/downscaling supported)
img_loadair([bpp [, flag]])imgDecode the latest incoming frame into an image object (firmware support required; see §6)
img_gif_load(picdata [, bpp])imgLoad GIF animation (streaming decoding)
img_gif_file(filename [, bpp])imgLoad GIF animation from a file (streaming decoding)
img_webpani_load(picdata [, bpp [, flag]])img, framesLoad WebP animation (streaming decoding)

Image Operations​

FunctionReturnsDescription
img_info(img)w, h, bpp, flag [, frame_h, delays]Get image information
img_airinfo()w, h, frame_id, jpg_len, age_msInspect latest incoming frame (no decoding; nil if absent)
airdata_get([prio])data, type, tag, sub, seq, remainingRemove the oldest receive-queue message (firmware support required, see §6)
airdata_send(type, data [, prio [, tag [, sub]]])booleanEnqueue a data message (firmware support required)
airdata_depth(dir [, prio])count, max_count, bytes, max_bytes, droppedQuery queue status (firmware support required)
airdata_clear(dir) / airdata_ready()cleared / booleanEmpty queues or check the connection (firmware support required)
img_set_flag(img, op, flag)flagSet image property flags
img_gif_palrefresh(img [, maxcnt])nRefresh VM palette from current GIF frame (4/8bpp only)
img_close(img)—Release image resources

Image Drawing​

FunctionDescription
img_draw(img, x, y [, opflag])Draw an image
img_drawex(img, x, y [, opflag, sx, sy, sw, sh])Draw an image region
img_drawrot(img, dx, dy, opflag [, sx, sy, sw, sh, angle, zoomx, zoomy])Draw with rotation and scaling
img_drawzoom(img, dx, dy, dw, dh [, sx, sy, sw, sh, opflag])Draw scaled to a specified size
img_scrair([x [, y [, flag]]])Decode latest incoming frame directly to screen (firmware support required; see §6)
img_drawgif(img, frameidx, x, y [, opflag, sx, sy, sw, sh])Draw a specified GIF frame

Animation Control​

FunctionReturnsDescription
img_gif_next(img [, force])has_next, delay_msDecode next streaming GIF frame
img_webpani_next(img [, force])has_next, delay_msDecode next streaming WebP frame
img_webpani_reset(img)—Reset WebP animation