# Images Every image format (PNG / APNG, JPEG, WebP, GIF, BMP, TGA, QOI, TIFF, ICO / CUR, PNM / PAM / PFM, Radiance HDR, OpenEXR, the [game textures](#game-textures) DDS / KTX / VTF / BLP / TIM, and the [older formats](#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 `Frame`s. Editing goes through `F.ops.image`. ```luau 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`: ```luau 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: ```luau 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`: ```luau 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 ```luau 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` | | `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 | To read only the header, use the format module's `info` on a reader (no pixels are decoded): ```luau 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. ```luau 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: ```luau 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`. ```luau 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") ``` ```luau 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`): ```luau 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") ``` Doom's graphics come from WAD lumps rather than files: `F.format("wad").image(wad, name)` (see [archive.md](archive.md#game-archives)). ## Formats Read and write unless noted; see [FORMATS.md](../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 | | 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. ```luau 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 `.R` / `.G` / ... ```luau 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](video.md). ## Showing an image ```luau local F = require(game.ReplicatedStorage.Formats) 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) ``` ```lua local F = require("formats") 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 also `gray8` / `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].image` is only the frame's rectangle. Use `F.ops.image.coalesce` to get full canvases. - GIF stores "repeat count" (plays - 1); `loops` is always the play count, so a loaded GIF that loops forever has `loops = 0` and a GIF without a loop extension has `loops = 1`. - A loaded GIF's `meta.background` is a palette index, while the WebP writer wants an `{ r, g, b, a }` colour: pass `background` explicitly when converting GIF to WebP: `F.save(gif, nil, { format = "webp", background = { 0, 0, 0, 0 } })`. - WebP writes lossless only (`lossless = false` returns `Err.UNSUPPORTED`). - `alpha8` images (font glyphs) convert to white with that alpha. - Pixel values are not colour managed: ICC profiles are kept in `meta.icc` but not applied.