50 lines
2.1 KiB
Luau
50 lines
2.1 KiB
Luau
-- examples/image.luau: build an image, edit it, save it in several formats, make an animated GIF (docs/guide/image.md).
|
|
-- On LuaJIT / LÖVE: local F = require("rosetta").
|
|
local F = require("@rosetta")
|
|
local I = F.ops.image
|
|
|
|
-- a 64 x 48 rgba8 gradient: 4 bytes per pixel, rows top to bottom, pixel (x, y) at byte (y * width + x) * 4
|
|
local img = F.Types.Image.new(64, 48)
|
|
for y = 0, 47 do
|
|
for x = 0, 63 do
|
|
local o = (y * 64 + x) * 4
|
|
buffer.writeu8(img.pixels, o, x * 4)
|
|
buffer.writeu8(img.pixels, o + 1, y * 5)
|
|
buffer.writeu8(img.pixels, o + 2, 128)
|
|
buffer.writeu8(img.pixels, o + 3, 255)
|
|
end
|
|
end
|
|
|
|
-- edit: a white square blitted on, then a thumbnail, a crop, a rotation and a grey copy
|
|
local square = assert(I.new(16, 16))
|
|
I.fill(square, 255, 255, 255, 200)
|
|
assert(I.blit(img, square, 24, 16))
|
|
local thumb = assert(I.resize(img, 32, 24, "lanczos"))
|
|
local corner = assert(I.crop(img, 0, 0, 16, 16))
|
|
local turned = assert(I.rotate90(img, 1))
|
|
local grey = assert(I.convert(img, "gray8"))
|
|
assert(thumb.width == 32 and corner.width == 16 and turned.width == 48 and grey.format == "gray8")
|
|
print(string.format("pixel (30, 20) after the blit: %d %d %d %d", I.getPixel(img, 30, 20)))
|
|
|
|
-- save in several formats and load each back
|
|
for _, fmt in { "png", "jpeg", "webp", "qoi", "bmp", "tga", "gif" } do
|
|
local bytes = assert(F.save(img, nil, { format = fmt }))
|
|
local back = assert(F.load(bytes))
|
|
assert(back.width == 64 and back.height == 48 and F.detect(bytes) == fmt)
|
|
print(string.format("%-5s %6d bytes", fmt, buffer.len(bytes)))
|
|
end
|
|
|
|
-- an animation: four frames, 0.1 s each, looping forever
|
|
local frames = {}
|
|
for i = 1, 4 do
|
|
frames[i] = assert(I.rotate90(thumb, (i - 1) * 2)) -- every frame the same size: 0 or 2 quarter turns
|
|
local marker = assert(I.new(4, 4))
|
|
I.fill(marker, 255, 0, 0)
|
|
I.blit(frames[i], marker, (i - 1) * 8, 0) -- a red marker that moves right
|
|
end
|
|
local anim = assert(I.fromFrames(frames, 0.1))
|
|
local gif = assert(F.save(anim, nil, { format = "gif" }))
|
|
local back = assert(F.load(gif))
|
|
assert(I.frameCount(back) == 4 and back.loops == 0)
|
|
print(string.format("animated gif: %d frames, %.1f s", I.frameCount(back), I.durations(back)[1] * 4))
|