Files
rosetta/docs/guide/recipes.md
T

167 lines
5.6 KiB
Markdown

# Recipes
Short task-oriented snippets. Each one runs as a test (see the [guide](README.md) for how the inputs such as
`pngBytes` are provided); the ones that read or write files run on hosts with a file system.
- [Images](#images): thumbnail, format conversion, GIF to video and back, show an image in Roblox or LÖVE
- [Audio](#audio): transcode, tags, game-loop streaming, render a MIDI
- [3D](#3d): glTF to OBJ with textures, voxels to a mesh
- [Other files](#other-files): zip, CSV, SVG, fonts
## Images
### Make a thumbnail
Fit the image into a 32 x 32 box, keeping its aspect ratio, and save it as a JPEG:
```luau
local img = assert(F.image.load(pngBytes))
local scale = math.min(32 / img.width, 32 / img.height, 1)
local w, h = math.max(1, math.floor(img.width * scale + 0.5)), math.max(1, math.floor(img.height * scale + 0.5))
local thumb = assert(F.ops.image.resize(img, w, h, "lanczos"))
local jpg = assert(F.save(thumb, nil, { format = "jpeg", quality = 85 }))
assert(thumb.width == 32 and thumb.height == 24 and F.detect(jpg) == "jpeg")
```
JPEG has no alpha channel. To keep transparency, save as PNG or WebP instead.
### Convert between image formats
```luau
local webp = assert(F.convert(pngBytes, "webp", { lossless = true }))
local back = assert(F.load(webp))
local orig = assert(F.load(pngBytes))
assert(buffer.tostring(back.pixels) == buffer.tostring(orig.pixels)) -- lossless: the same pixels
```
### Animated GIF to video and back to frames
An animated image converts to a video directly. AVI and MP4 store Motion-JPEG frames.
```luau
local avi = assert(F.convert(gifBytes, "avi"))
local mp4 = assert(F.convert(gifBytes, "mp4", { quality = 90 }))
assert(F.detect(avi) == "avi" and F.detect(mp4) == "mp4")
local v = assert(F.video.open(avi))
local frames = {}
while true do
local f = v:nextFrame()
if not f then
break
end
table.insert(frames, v:toRGBA(f)) -- each frame as an rgba8 Image
end
assert(#frames >= 3 and frames[1].width == 32)
local gif = assert(F.save(assert(F.ops.image.fromFrames(frames, 1 / v.frameRate)), nil, { format = "gif" }))
assert(F.detect(gif) == "gif")
```
The GIF frames of `gifBytes` are full-canvas, so the frames you get back match the GIF's. GIF delays that are not a
whole number of video frames become repeated frames.
### Every frame of an animation as a full image
```luau
local gif = assert(F.image.load(gifBytes))
local canvases = assert(F.ops.image.coalesce(gif)) -- frames composited onto full canvases
local delays = F.ops.image.durations(gif) -- seconds per frame
assert(#canvases == F.ops.image.frameCount(gif) and #delays == #canvases)
for i, frame in canvases do
local png = assert(F.save(frame, nil, { format = "png" }))
local _ = png, i -- e.g. F.save(frame, "frame" .. i .. ".png")
end
```
### Show an image in Roblox
<!-- doc:display needs Roblox -->
```luau
local F = require(game:GetService("ReplicatedStorage").Formats)
local bytes = game:GetService("HttpService"):GetAsync("https://example.com/cat.webp")
local img = assert(F.image.load(bytes))
if img.format ~= "rgba8" then
img = assert(F.ops.image.convert(img, "rgba8"))
end
local editable = assert(F.host.toEditableImage(img))
local label = Instance.new("ImageLabel")
label.Size = UDim2.fromOffset(img.width, img.height)
label.ImageContent = Content.fromObject(editable)
label.Parent = game:GetService("Players").LocalPlayer.PlayerGui:WaitForChild("ScreenGui")
```
### Show an image in LÖVE
<!-- doc:display needs LÖVE -->
```lua
local F = require("formats")
local image
function love.load()
local img = assert(F.load("cat.webp")) -- a love.filesystem path
image = love.graphics.newImage(F.host.toImageData(img))
end
function love.draw()
love.graphics.draw(image, 0, 0)
end
```
## Audio
### Transcode FLAC to MP3
`F.convert` streams audio: the encoder reads the decoder as it goes.
```luau
local mp3 = assert(F.convert(flacBytes, "mp3", { bitrate = 192 })) -- MP3 bit rates are in kbit/s
local dec = assert(F.audio.open(mp3))
assert(dec.sampleRate == 44100 and dec.channels == 2)
assert(math.abs(dec.duration - 1) < 0.1)
```
### Read the tags of any audio file
Tag keys are lower case (`title`, `artist`, `album`, `date`, `genre`, `track`, `comment`, ...), whatever the
container calls them.
```luau
for _, bytes in { flacBytes, mp3Bytes, oggBytes } do
local dec = assert(F.audio.open(bytes)) -- open reads the headers only
assert(dec.tags.title == "Docs Tone" and dec.tags.artist == "formats-luau")
print(string.format("%s - %s (%.1f s, %d Hz)", dec.tags.artist, dec.tags.title, dec.duration, dec.sampleRate))
end
```
### Stream decode with a CPU budget per frame
In a game loop, decode a little each frame instead of everything at once. Read in small blocks, stop when the time
budget for this frame is used up, and continue next frame. `os.clock()` works on every host, Roblox included.
```luau
local dec = assert(F.audio.open(oggBytes))
local block = buffer.create(1024 * dec.channels * 4) -- reused for every read
local decoded = 0
local function step(budget: number): boolean -- call once per frame; false when finished
local t0 = os.clock()
while os.clock() - t0 < budget do
local out, n = dec:read(1024, block)
if n == 0 then
return false
end
decoded += n -- hand out[0 .. n * channels * 4) to the mixer here
local _ = out
end
return true
end
while step(0.002) do end -- in a game: RunService.Heartbeat / love.update
assert(decoded == dec.frames)
```
The same pattern works for video: call `v:nextFrame()` until the budget is used up or the next frame's `pts` is in
the future.
## 3D
## Other files