init.luau (small, backward compatible): loadTextures forwards those four options to F.load.
22 KiB
Images
Every image format (PNG / APNG, JPEG, WebP, GIF, BMP, TGA, QOI, TIFF, ICO / CUR, PNM / PAM / PFM, Radiance HDR,
OpenEXR, the game textures DDS / KTX / VTF / BLP / TIM / ART, and the older formats PCX, SGI,
Sun Raster, ILBM, XPM, XBM, ICNS, ANI) loads as one Image: a width, a height, a pixel format and one tightly packed buffer. Animations (GIF, APNG, animated
WebP) and multi-image files (TIFF pages, ICO entries) add a list of Frames. Editing goes through F.ops.image.
local img = assert(F.image.load(pngBytes)) -- buffer, string, or a path on hosts with files
print(img.width, img.height, img.format) -- 64 48 rgba8
local thumb = assert(F.ops.image.resize(img, 32, 24, "lanczos"))
local jpg = assert(F.save(thumb, nil, { format = "jpeg", quality = 85 }))
assert(F.detect(jpg) == "jpeg")
The type
Image
| Field | Type | Meaning |
|---|---|---|
kind |
"image" |
|
width, height |
number | pixels, both >= 1 for decoded images |
format |
string | the pixel format (below); decoders give "rgba8" unless opts.native asks otherwise |
pixels |
buffer | rows top to bottom, pixels left to right, no padding between rows |
frames |
{ Frame }? |
animations / pages / icon entries; nil for a still image |
loops |
number | play count of an animation: 0 = forever, 1 = once, n = n plays |
meta |
table | source ({ format, bitDepth?, colorType?, ... }), and when the file has them: icc (buffer), exif (buffer, from the TIFF header on), dpi ({ x, y }), palette ({ { r, g, b, a } }), text ({ [key]: string }), orientation (JPEG EXIF, 1..8) |
Pixel formats (F.Types.BPP[format] is the bytes per pixel):
format |
Bytes / pixel | Layout of one pixel | Range |
|---|---|---|---|
rgba8 |
4 | R, G, B, A bytes | 0..255, straight (not premultiplied) alpha |
rgb8 |
3 | R, G, B | 0..255 |
gray8 |
1 | luma | 0..255 |
graya8 |
2 | luma, alpha | 0..255 |
alpha8 |
1 | alpha (glyph coverage) | 0..255 |
gray16 |
2 | luma, u16 little endian | 0..65535 |
rgba16 |
8 | R, G, B, A as u16 little endian | 0..65535 |
rgbaf32 |
16 | R, G, B, A as f32 little endian | linear, 0..1 nominal (HDR may exceed 1) |
yuv420p |
planar | Y plane w * h, then U and V planes ceil(w/2) * ceil(h/2) each |
BT.601 full range unless meta.yuv says otherwise |
For a packed format the pixel (x, y) (0-based, origin top left) starts at byte (y * width + x) * bpp:
local img = assert(F.load(pngBytes))
local x, y = 10, 5
local o = (y * img.width + x) * 4 -- rgba8
local r, g, b, a = buffer.readu8(img.pixels, o), buffer.readu8(img.pixels, o + 1),
buffer.readu8(img.pixels, o + 2), buffer.readu8(img.pixels, o + 3)
assert(buffer.len(img.pixels) == img.width * img.height * 4)
assert(select(1, F.ops.image.getPixel(img, x, y)) == r) -- the same pixel, through ops
local _ = g + b + a
Frame (one entry of img.frames)
| Field | Type | Meaning |
|---|---|---|
image |
Image | the frame's own rectangle (not the full canvas) |
x, y |
number | where that rectangle sits on the width x height canvas |
delay |
number | seconds the frame stays on screen |
dispose |
"none" / "background" / "previous" |
what happens to the frame's rectangle before the next frame: keep it, clear it to transparent, or restore what was there before |
blend |
"source" / "over" |
replace the canvas pixels, or alpha-composite over them |
For an animation, img.pixels is the first frame already composited onto the canvas, so code that ignores frames
still gets a sensible still image. F.ops.image.coalesce(img) composites every frame for you:
local gif = assert(F.load(gifBytes))
print(#gif.frames, gif.loops) -- 3 0 (forever)
local canvases = assert(F.ops.image.coalesce(gif)) -- { Image }: full width x height rgba8, one per frame
assert(#canvases == 3 and canvases[2].width == gif.width)
local delays = F.ops.image.durations(gif) -- { 0.1, 0.1, 0.1 }
assert(F.ops.image.frameCount(gif) == 3 and delays[1] == 0.1)
Make an image from scratch with F.Types.Image.new(w, h, format?) (zero-filled, so transparent black) or
F.ops.image.new:
local img = F.Types.Image.new(16, 16) -- rgba8
F.ops.image.fill(img, 255, 128, 0) -- opaque orange (alpha defaults to opaque)
F.ops.image.setPixel(img, 0, 0, 0, 0, 0, 0) -- one transparent pixel
local png = assert(F.save(img, nil, { format = "png" }))
assert(F.load(png).width == 16)
Load
local img, err = F.load(pngBytes) -- any category: detected from the content
local same = F.image.load(pngBytes) -- restricted to image formats
local jpg = F.image.load(jpegBytes, { scale = 2 }) -- JPEG: decode at half size (2, 4 or 8)
assert(jpg.width == 32)
local tooBig, lerr = F.load(pngBytes, { maxPixels = 100 })
assert(tooBig == nil and lerr.code == F.Err.LIMIT)
local _ = img and same and err
| Option | Formats | Meaning |
|---|---|---|
format |
all | decode as this format (name or extension) instead of sniffing |
maxPixels |
all | refuse larger images with Err.LIMIT (default 2^26) |
native |
JPEG, WebP, TIFF, PNM, QOI, TGA, HDR | keep the source layout: gray8 / gray16 / rgb8 / rgba16 / rgbaf32 / yuv420p (lossy WebP) instead of rgba8 |
maxSide |
PNG, JPEG | decode straight to a smaller image whose sides are at most this (below) |
reduce |
PNG | box reduction by this power of two |
yield, yieldRows |
PNG, JPEG | cooperative yield hook for long decodes (below) |
scale, orient |
JPEG | reduced-size decode; apply the EXIF orientation (meta.orientation reports it either way) |
coalesce, frames |
WebP | every frame as a full canvas; frames = false decodes only the first |
page, maxPages |
TIFF | decode one page (1-based); cap on pages in frames |
maxFrames |
GIF | cap on frames |
Huge textures: maxSide and yield
A 4096 x 4096 16-bit PNG normal map is about 100 MB inflated and 64 MB as an rgba8 Image. With maxSide, PNG and
JPEG shrink the picture while decoding, so the full-size image is never built:
- PNG reduces by the smallest power of two
kthat brings both sides tomaxSideor less (ceil(side / k)), so the result can be up to half ofmaxSide: 4096 withmaxSide = 1024gives 1024, 3000 gives 750. Each output pixel is the alpha-weighted mean of its k x k block (16-bit samples are cut to 8 bits first, as a full decode does; smaller blocks at the right and bottom edges; halves round up; a fully transparent block is0, 0, 0, 0). Rows stream through the inflater, so memory is the output plus a few rows. Interlaced (Adam7) PNGs still inflate and decode at full size before the reduction. APNG frames are reduced one by one, their offsets divided byk.reduce = kasks for a factor directly;meta.source.reducereports the one used andmeta.source.width/heightthe original size. - JPEG picks the smallest DCT scale (1/2, 1/4, 1/8) that fits, the same as
scale: pixels are bit-exact with libjpeg-turbo'sdjpeg -scale 1/n. Below 1/8 it stops at 1/8. The coefficients are still stored at full size (2 bytes per pixel and component).
For an exact size (e.g. Roblox's 1024 EditableImage cap), follow with F.ops.image.resize.
yield is called through pcall every yieldRows rows (PNG; default: about 64 KB of row data) or every MCU row and
block row (JPEG), so a decode inside a coroutine can give the frame back. On Roblox, call task.wait() from it in a
task.spawned thread once a time budget is spent; the same with coroutine.yield everywhere:
local small = assert(F.image.load(pngBytes, { maxSide = 16 })) -- 64 x 48 -> 16 x 12 (k = 4)
assert(small.width == 16 and small.height == 12 and small.meta.source.reduce == 4)
local thumb = assert(F.image.load(jpegBytes, { maxSide = 16 })) -- JPEG at 1/4
assert(thumb.width == 16 and thumb.meta.source.scale == 4)
local budget, start = 0.004, os.clock()
local co = coroutine.wrap(function(): any
return F.image.load(pngBytes, { maxSide = 32, yieldRows = 4, yield = function()
if os.clock() - start > budget then
coroutine.yield() -- Roblox: task.wait()
start = os.clock()
end
end })
end)
local img = co()
while img == nil do -- once per frame
img = co()
end
assert(img.width == 32)
To read only the header, use the format module's info on a reader (no pixels are decoded):
local info = assert(F.format("png").info(F.Bytes.reader(pngBytes)))
assert(info.width == 64 and info.height == 48 and info.bitDepth == 8)
Edit with F.ops.image
Every function returns a new Image (or nil, err) unless it says "in place". Inputs may be any pixel format;
geometric operations on yuv420p go through rgba8.
local img = assert(F.load(pngBytes))
local ops = F.ops.image
local small = assert(ops.resize(img, 32, 24)) -- filter: "bilinear" (default), "nearest", "lanczos"
local part = assert(ops.crop(img, 8, 8, 16, 16)) -- x, y, w, h (clipped to the image)
local mirrored = assert(ops.flip(img, "h")) -- "h" left-right, "v" top-bottom
local turned = assert(ops.rotate90(img, 1)) -- quarter turns counter-clockwise (-1 = clockwise)
local tilted = assert(ops.rotate(img, 30)) -- degrees counter-clockwise, canvas grows (opts.expand)
local grey = assert(ops.convert(img, "gray8")) -- any pixel format to any other
assert(turned.width == 48 and grey.format == "gray8" and tilted.width > 64)
local canvas = assert(ops.new(64, 64))
ops.blit(canvas, part, 4, 4) -- in place, alpha "over" (opts.blend = "source" copies)
ops.blit(canvas, small, 30, 30, { opacity = 0.5 })
local merged = assert(ops.composite(canvas, mirrored, -32, 40)) -- a copy of canvas with the image drawn on it
local pm = assert(ops.premultiply(img)) -- and ops.unpremultiply
local r, g, b, a = ops.getPixel(img, 63, 0) -- in the format's scale (0..255 / 0..65535 / float)
assert(a == 128 and select(4, ops.getPixel(pm, 63, 0)) == 128)
local copy = assert(ops.copy(img))
ops.setPixel(copy, 0, 0, 255, 0, 0) -- in place; alpha defaults to opaque
local _ = merged and r and g and b
Conversions: 8 <-> 16 bit multiplies / divides by 257, float <-> integer clamps to 0..1 (no gamma), grey uses
(19595 R + 38470 G + 7471 B + 32768) >> 16.
Animations:
local ops = F.ops.image
local a = assert(ops.new(8, 8))
local b = assert(ops.fill(assert(ops.new(8, 8)), 255, 0, 0))
local anim = assert(ops.fromFrames({ a, b }, 0.5)) -- delays: one number or { seconds }
assert(#anim.frames == 2 and anim.frames[2].delay == 0.5)
anim.loops = 3
local gif = assert(F.save(anim, nil, { format = "gif" }))
assert(F.load(gif).loops == 3)
Save and convert
F.save(img, dest?, opts?) picks the writer from opts.format, else from the extension of dest, else from
img.meta.source.format (the format it was loaded from). Without dest it returns the encoded buffer.
local img = assert(F.load(pngBytes))
local again = assert(F.save(img)) -- PNG again: the source format
local q = assert(F.save(img, nil, { format = "qoi" }))
local s = assert(F.saveString(img, { format = "bmp" })) -- a string instead of a buffer
local webp = assert(F.convert(pngBytes, "webp", { effort = 9 })) -- load + save in one call
assert(F.detect(again) == "png" and F.detect(q) == "qoi" and string.sub(s, 1, 2) == "BM" and F.detect(webp) == "webp")
local img = assert(F.load("assets/photo.png")) -- a path (LuaJIT / LÖVE)
assert(F.save(img, "out/photo.jpg", { quality = 80 })) -- format from the extension; returns true
assert(F.convert("assets/anim.gif", "png", { out = "out/anim.png" })) -- an APNG
assert(F.load("out/anim.png").frames ~= nil)
Encoder options:
| Format | Options |
|---|---|
| PNG | level (deflate 0..9, default 6), colorType ("auto": smallest of RGBA / RGB / grey / grey + alpha), apng (write an APNG; automatic when frames is set) |
| JPEG | quality (1..100, default 90), subsampling ("420" / "422" / "444"), progressive, optimize, restart, jfif, meta (write EXIF / ICC / comment) |
| WebP | lossless only: effort (0..9, default 5), exact (keep RGB under transparent pixels), loops, background ({ r, g, b, a }) |
| GIF | maxColors (default 256), method ("mediancut" / "octree"), dither, loops, globalPalette |
| TIFF | compression ("deflate" default, "lzw", "packbits", "none"), predictor, level, rowsPerStrip; frames become pages |
| BMP | header ("v4" default, "info") |
| TGA | rle, origin ("bottom-left" / "top-left") |
| ICO | cursor, png (PNG entries); frames become entries (each up to 256 x 256) |
| PNM | the subtype from the extension or format: pbm, pgm, ppm, pam, pfm |
Game textures
PlayStation TIM, Blizzard BLP and Valve VTF load as Images too (rgba8; the mip and texel facts in
meta.source):
local face = assert(F.image.load(timBytes)) -- 4 / 8-bit CLUT, 15 or 24-bit
assert(face.meta.source.bpp == 16)
local tim = assert(F.save(face, nil, { format = "tim", bpp = 16 })) -- TIM writes 4 / 8 / 16 / 24-bit
local icon = assert(F.image.load(blpBytes)) -- BLP1 JPEG / palette, BLP2 palette / DXT / BGRA
assert(icon.width == 4 and icon.meta.source.compression == "bgra")
local wall = assert(F.image.load(vtfBytes)) -- every common VTF texel format, frames, mips
assert(wall.meta.source.texel == "RGBA8888")
local small = assert(F.image.load(vtfBytes, { mip = 1 })) -- or face = n (cube maps), slice = n (volumes)
assert(F.detect(tim) == "tim")
Build engine ART files (TILES000.ART ..., Duke Nukem 3D, Shadow Warrior) hold many tiles: each is one entry of
frames (in tile order, empty tiles 0 x 0), with its tile number in meta.tile and its picanm animation and centre
offsets in meta.picanm; the top-level image is the first non-empty tile. Colours come from the game's
PALETTE.DAT, passed as palette or found next to the file through resolve (without it the tiles decode as a grey
ramp). Index 255 is transparent. shade / pal apply a PALETTE.DAT shade table / a LOOKUP.DAT palookup, native
keeps the palette indices (gray8), and ART writes back from either form:
local tiles = assert(F.image.load(artBytes, { palette = paletteBytes }))
local second = tiles.frames[2].image
assert(second.meta.tile == 1 and second.width == 8)
assert(second.meta.picanm.type == "forward" and second.meta.picanm.frames == 2)
local raw = assert(F.image.load(artBytes, { format = "art", native = true }))
assert(raw.frames[1].image.format == "gray8")
assert(buffer.tostring(assert(F.save(raw, nil, { format = "art" }))) == buffer.tostring(artBytes))
Doom's graphics come from WAD lumps rather than files: F.format("wad").image(wad, name) (see
archive.md).
Quake's .lmp pictures (qpics), palette.lmp and colormap.lmp, and Quake / Half-Life sprites (.spr) load
too. Quake pictures and sprites are 8-bit images over Quake's palette, which is not redistributable: pass it as
palette (768 bytes) or as gfx/palette.lmp through files / resolve (without it they load grey,
meta.source.palette = false). Half-Life sprites carry their own palette. Sprite frames are img.frames on one
canvas around the sprite's origin (meta.origin); frame groups give the delays.
local disc = assert(F.image.load(discLmpBytes, { name = "disc.lmp", palette = quakePaletteBytes }))
assert(disc.width == 24 and disc.meta.source.palette) -- index 255 is transparent
local pal = assert(F.image.load(quakePaletteBytes, { format = "lmp" })) -- a 16 x 16 swatch
assert(#pal.meta.palette == 256)
local back = assert(F.save(disc, nil, { format = "lmp", palette = quakePaletteBytes }))
assert(buffer.len(back) == buffer.len(discLmpBytes))
local flame = assert(F.image.load(flameSprBytes)) -- Half-Life: its own palette
assert(#flame.frames == 3 and flame.meta.source.texFormat == "alphatest")
local spr = assert(F.save(flame, nil, { format = "spr" })) -- version 2; version = 1 (Quake) needs palette
assert(#F.image.load(spr).frames == 3)
Doom's graphics come from WAD lumps rather than files: F.format("wad").image(wad, name), and Quake / Half-Life
textures from WAD2 / WAD3: F.format("wad2").image(wad, name) (see archive.md).
Formats
Read and write unless noted; see FORMATS.md for depths and details.
| Format | Animation / pages | Alpha | Notes |
|---|---|---|---|
| PNG / APNG | APNG frames | yes | writes rgba8 only |
| JPEG | no | lossy; reads baseline / progressive / arithmetic, 8 and 12 bit | |
| WebP | frames | yes | reads lossy + lossless; writes lossless only |
| GIF | frames | 1-bit | writes through a palette quantizer (exact when <= 256 colours) |
| TIFF | pages | yes | 1..32-bit, float |
| BMP, TGA, QOI, ICO / CUR, PNM / PAM / PFM | ICO entries | yes | |
| HDR | no | float (native gives rgbaf32) |
|
| TIM | yes | PlayStation; 4 / 8-bit CLUT, 15 / 24-bit | |
| BLP | yes | Blizzard BLP1 / BLP2 (DXT through the BCn codec); writes BLP2 BGRA | |
| VTF | frames | yes | Valve; read only; mips / faces / slices by option |
| ART | tiles as frames | index 255 | Build engine tiles; palette from PALETTE.DAT (palette / resolve), picanm in meta.picanm |
| DDS, KTX / KTX2 | faces / layers / slices | yes | GPU textures: BC1..BC7, ETC / EAC, every uncompressed layout; mips in meta.mipmaps |
| OpenEXR | parts (opts.part) |
yes | half / float / uint, NONE / RLE / ZIPS / ZIP / PIZ, tiles; writes NONE / ZIPS / ZIP |
| PCX, SGI, Sun Raster, IFF ILBM / PBM, XPM, XBM | yes (XBM 1-bit) | old paint / workstation formats; ILBM reads HAM and EHB | |
| ICNS, ANI | ICNS sizes / ANI steps | yes | PNG / ICO entries through the api hooks |
Textures and HDR (DDS, KTX, EXR)
DDS and KTX files hold GPU textures: block-compressed (BC1..BC7, ETC1 / ETC2 / EAC) or plain texel layouts, with mip
levels, cube faces and array layers. The image is the first surface; img.frames lists every face / layer / depth
slice when there is more than one (meta.layout is "2d", "cube", "array" or "volume"), and with opts.mips the
smaller levels of the first surface go to meta.mipmaps. Float and 16-bit sources keep their values with
opts.native (rgbaf32 / rgba16); otherwise they are clamped into rgba8. Writers pick the stored layout with
pixelFormat (format is the file format): DDS writes rgba8, bgra8, bc1, bc3, bc4, bc5, rgba16,
rgba16f, rgba32f; KTX2 writes the uncompressed ones.
local img = assert(F.ops.image.new(64, 64))
assert(F.ops.image.fill(img, 200, 120, 40, 255))
local dds = assert(F.save(img, nil, { format = "dds", pixelFormat = "bc1", mips = true }))
local tex = assert(F.load(dds, { mips = true }))
assert(tex.meta.source.pixelFormat == "bc1" and #tex.meta.mipmaps == 6)
local ktx = assert(F.save(img, nil, { format = "ktx", mips = true, zlib = 6 })) -- KTX2, ZLIB-supercompressed
assert(F.detect(ktx) == "ktx")
OpenEXR loads as linear floats with opts.native (rgbaf32); the default rgba8 goes through the same 1 / 2.2
display curve as Radiance HDR. opts.part picks a part of a multipart file, opts.layer reads <layer>.R / .G / ...
local hdr = assert(F.ops.image.new(8, 8, "rgbaf32"))
assert(F.ops.image.fill(hdr, 4, 2, 0.5, 1)) -- floats may exceed 1
local exr = assert(F.save(hdr, nil, { format = "exr", compression = "zip", pixelType = "half" }))
local linear = assert(F.load(exr, { native = true }))
assert(linear.format == "rgbaf32" and math.abs(buffer.readf32(linear.pixels, 0) - 4) < 1e-3)
assert(F.load(exr).format == "rgba8") -- the display conversion
An animated image also opens as a video (F.video.open(gifBytes)), and saves to a video format
(F.convert(gifBytes, "avi")): see video.md.
Showing an image
local F = require(game.ReplicatedStorage.Rosetta)
local img = assert(F.image.load(pngBuffer)) -- e.g. from HttpService:GetAsync(...)
local editable = assert(F.host.toEditableImage(img)) -- needs rgba8: F.ops.image.convert first otherwise
local label = Instance.new("ImageLabel")
label.ImageContent = Content.fromObject(editable)
local F = require("rosetta")
local img = assert(F.load("photo.png")) -- love.filesystem path
local image = love.graphics.newImage(F.host.toImageData(img))
local back = F.host.fromImageData(love.image.newImageData("other.png")) -- ImageData -> rgba8 Image
Gotchas
- Encoders take
rgba8(JPEG alsogray8/yuv420p; TIFF, PNM and HDR more): convert first, e.g.F.save(F.ops.image.convert(img16, "rgba8"), nil, { format = "png" }). PNG writing of 16-bit or palette images is not supported; 16-bit PNGs decode to 8 bits. frames[i].imageis only the frame's rectangle. UseF.ops.image.coalesceto get full canvases.- GIF stores "repeat count" (plays - 1);
loopsis always the play count, so a loaded GIF that loops forever hasloops = 0and a GIF without a loop extension hasloops = 1. - A loaded GIF's
meta.backgroundis a palette index, while the WebP writer wants an{ r, g, b, a }colour: passbackgroundexplicitly when converting GIF to WebP:F.save(gif, nil, { format = "webp", background = { 0, 0, 0, 0 } }). - WebP writes lossless only (
lossless = falsereturnsErr.UNSUPPORTED). alpha8images (font glyphs) convert to white with that alpha.- Pixel values are not colour managed: ICC profiles are kept in
meta.iccbut not applied.