Files
rosetta/src/Rosetta/ops/ImageOps/init.luau
T
2026-11-01 01:57:14 -05:00

643 lines
20 KiB
Luau

--!strict
-- ops/ImageOps: editing on the standard Image: conversion, crop, resize, flips, rotation, compositing, pixel access,
-- animation helpers. New code; the resampling and compositing follow Pillow's C sources.
-- Conventions: angles are degrees counter-clockwise and rotate90 turns are counter-clockwise quarter turns (as
-- Pillow). Resizing and rotating filter premultiplied alpha (as Pillow does for RGBA / LA). Grey is Pillow's
-- L = (19595 R + 38470 G + 7471 B + 32768) >> 16. 8 <-> 16 bit is * 257 and
-- (v * 255 + 32767) // 65535; float <-> integer clamps to 0..1 and rounds (no gamma). alpha8 converts to white with
-- that alpha. yuv420p is JPEG-style BT.601 full range (2x2 box chroma); geometric ops on yuv420p go through rgba8.
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local K = require("@rosetta/ops/ImageOps/Kernels")
local ImageOps = {}
local MAX_PIXELS = 2 ^ 26
type Image = Types.Image
local function arg(msg: string): (nil, Err.Err)
return nil, Err.new(Err.ARG, msg)
end
local function isInt(v: any): boolean
return type(v) == "number" and v == v and v % 1 == 0 and v > -2 ^ 31 and v < 2 ^ 31
end
local function bytesOf(fmt: string, w: number, h: number): number?
if fmt == "yuv420p" then
return w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2)
end
local bpp = Types.BPP[fmt]
return if bpp then w * h * bpp else nil
end
local function check(img: any): (boolean?, Err.Err?)
if type(img) ~= "table" or type(img.pixels) ~= "buffer" then
return arg("expected an Image")
end
if not isInt(img.width) or not isInt(img.height) or img.width < 1 or img.height < 1 then
return arg("bad image size")
end
local need = bytesOf(img.format, img.width, img.height)
if not need then
return arg("unknown pixel format " .. tostring(img.format))
end
if buffer.len(img.pixels) < need then
return arg("pixel buffer too small for " .. img.width .. " x " .. img.height .. " " .. img.format)
end
return true, nil
end
ImageOps.check = check
local function limit(w: number, h: number, opts: any): (boolean?, Err.Err?)
local max: number = (type(opts) == "table" and opts.maxPixels) or MAX_PIXELS
if w * h > max then
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, max))
end
return true, nil
end
local function like(img: Image, w: number, h: number, fmt: string?): Image
local out = Types.Image.new(w, h, (fmt or img.format) :: any)
for k, v in img.meta do
out.meta[k] = v
end
out.loops = img.loops
return out
end
function ImageOps.new(w: number, h: number, format: string?): (Image?, Err.Err?)
local fmt = format or "rgba8"
if not isInt(w) or not isInt(h) or w < 1 or h < 1 then
return arg("bad image size")
end
if not bytesOf(fmt, 1, 1) then
return arg("unknown pixel format " .. tostring(fmt))
end
local ok, e = limit(w, h, nil)
if not ok then
return nil, e
end
return Types.Image.new(w, h, fmt :: any), nil
end
function ImageOps.copy(img: Image): (Image?, Err.Err?)
local ok, e = check(img)
if not ok then
return nil, e
end
local out = like(img, img.width, img.height)
buffer.copy(out.pixels, 0, img.pixels, 0, buffer.len(out.pixels))
out.frames = img.frames
return out, nil
end
function ImageOps.convert(img: Image, format: string): (Image?, Err.Err?)
local ok, e = check(img)
if not ok then
return nil, e
end
if not bytesOf(format, 1, 1) then
return arg("unknown pixel format " .. tostring(format))
end
local w, h = img.width, img.height
if img.format == format then
return ImageOps.copy(img)
end
local src = img
if img.format == "yuv420p" then
local rgba = like(img, w, h, "rgba8")
K.yuvToRgba(img.pixels, w, h, rgba.pixels)
if format == "rgba8" then
return rgba, nil
end
src = rgba
end
local out = like(img, w, h, format)
if format == "yuv420p" then
local rgba = src
if src.format ~= "rgba8" then
rgba = like(img, w, h, "rgba8")
K.convert(src.pixels, K.ID[src.format], rgba.pixels, K.ID.rgba8, w * h)
end
K.rgbaToYuv(rgba.pixels, w, h, out.pixels)
return out, nil
end
K.convert(src.pixels, K.ID[src.format], out.pixels, K.ID[format], w * h)
return out, nil
end
-- ops on yuv420p run on rgba8 and convert back
local function viaRgba(img: Image, f: (Image) -> (Image?, Err.Err?)): (Image?, Err.Err?)
if img.format ~= "yuv420p" then
return f(img)
end
local rgba = ImageOps.convert(img, "rgba8") :: Image
local res, e = f(rgba)
if not res then
return nil, e
end
return ImageOps.convert(res, "yuv420p")
end
local ALPHA_CH: { [string]: number } = { rgba8 = 4, rgba16 = 4, rgbaf32 = 4, graya8 = 2 }
function ImageOps.crop(img: Image, x: number, y: number, w: number, h: number): (Image?, Err.Err?)
local ok, e = check(img)
if not ok then
return nil, e
end
if not (isInt(x) and isInt(y) and isInt(w) and isInt(h)) then
return arg("crop: integer x, y, w, h")
end
local x0, y0 = math.max(0, x), math.max(0, y)
local x1, y1 = math.min(img.width, x + w), math.min(img.height, y + h)
if x1 <= x0 or y1 <= y0 then
return arg("crop: the rectangle is outside the image or empty")
end
return viaRgba(img, function(im: Image): (Image?, Err.Err?)
local bpp = Types.BPP[im.format] :: number
local out = like(im, x1 - x0, y1 - y0)
K.copyRect(out.pixels, out.width, im.pixels, im.width, x0, y0, 0, 0, out.width, out.height, bpp)
return out, nil
end)
end
function ImageOps.flip(img: Image, axis: string): (Image?, Err.Err?)
local ok, e = check(img)
if not ok then
return nil, e
end
if axis ~= "h" and axis ~= "v" then
return arg("flip: axis must be \"h\" or \"v\"")
end
return viaRgba(img, function(im: Image): (Image?, Err.Err?)
local out = like(im, im.width, im.height)
K.flip(im.pixels, out.pixels, im.width, im.height, Types.BPP[im.format] :: number, axis == "h")
return out, nil
end)
end
function ImageOps.rotate90(img: Image, turns: number): (Image?, Err.Err?)
local ok, e = check(img)
if not ok then
return nil, e
end
if not isInt(turns) then
return arg("rotate90: integer turns")
end
local t = turns % 4
if t == 0 then
return ImageOps.copy(img)
end
return viaRgba(img, function(im: Image): (Image?, Err.Err?)
local swap = t ~= 2
local out = like(im, if swap then im.height else im.width, if swap then im.width else im.height)
K.rotate90(im.pixels, out.pixels, im.width, im.height, Types.BPP[im.format] :: number, t)
return out, nil
end)
end
export type ResizeFilter = "nearest" | "bilinear" | "lanczos"
function ImageOps.resize(img: Image, w: number, h: number, filter: string?, opts: any?): (Image?, Err.Err?)
local ok, e = check(img)
if not ok then
return nil, e
end
if not isInt(w) or not isInt(h) or w < 1 or h < 1 then
return arg("resize: bad target size")
end
local f = filter or "bilinear"
if f ~= "nearest" and f ~= "bilinear" and f ~= "lanczos" then
return arg("resize: filter must be nearest, bilinear or lanczos")
end
local lok, le = limit(w, h, opts)
if not lok then
return nil, le
end
return viaRgba(img, function(im: Image): (Image?, Err.Err?)
local fmt = im.format
local bpp = Types.BPP[fmt] :: number
local out = like(im, w, h)
if f == "nearest" then
K.nearest(im.pixels, im.width, im.height, bpp, out.pixels, w, h)
return out, nil
end
local kind, ch = K.KIND[fmt], K.CHANNELS[fmt]
local src, sw, sh = im.pixels, im.width, im.height
local alpha = ALPHA_CH[fmt]
if alpha then
src = buffer.create(buffer.len(im.pixels))
buffer.copy(src, 0, im.pixels)
K.premultiply(src, sw * sh, alpha, kind, false)
end
if w ~= sw then
local tmp = buffer.create(w * sh * bpp)
K.resamplePass(src, sw, sh, ch, kind, tmp, w, K.coeffs(sw, w, f), true)
src, sw = tmp, w
end
if h ~= sh then
K.resamplePass(src, sw, sh, ch, kind, out.pixels, h, K.coeffs(sh, h, f), false)
elseif src == im.pixels or (w == im.width and alpha) then
buffer.copy(out.pixels, 0, im.pixels, 0, w * h * bpp)
return out, nil
else
out.pixels = src
end
if alpha then
K.premultiply(out.pixels, w * h, alpha, kind, true)
end
return out, nil
end)
end
function ImageOps.rotate(img: Image, degrees: number, opts: { expand: boolean?, maxPixels: number? }?): (Image?, Err.Err?)
local ok, e = check(img)
if not ok then
return nil, e
end
if type(degrees) ~= "number" or degrees ~= degrees or degrees == math.huge or degrees == -math.huge then
return arg("rotate: degrees must be a finite number")
end
local expand = not (opts and opts.expand == false)
if degrees % 90 == 0 and (expand or degrees % 180 == 0 or img.width == img.height) then
return ImageOps.rotate90(img, (degrees // 90) % 4)
end
local w, h = img.width, img.height
local ang = -math.rad(degrees)
local function r15(v: number): number
return math.floor(v * 1e15 + 0.5) / 1e15
end
local m = { r15(math.cos(ang)), r15(math.sin(ang)), 0, r15(-math.sin(ang)), r15(math.cos(ang)), 0 }
local function tr(x: number, y: number): (number, number)
return m[1] * x + m[2] * y + m[3], m[4] * x + m[5] * y + m[6]
end
local cx, cy = w / 2, h / 2
m[3], m[6] = tr(-cx, -cy)
m[3] += cx
m[6] += cy
local nw, nh = w, h
if expand then
local xs, ys = {}, {}
for _, p in { { 0, 0 }, { w, 0 }, { w, h }, { 0, h } } do
local x, y = tr(p[1], p[2])
table.insert(xs, x)
table.insert(ys, y)
end
nw = math.ceil(math.max(xs[1], xs[2], xs[3], xs[4])) - math.floor(math.min(xs[1], xs[2], xs[3], xs[4]))
nh = math.ceil(math.max(ys[1], ys[2], ys[3], ys[4])) - math.floor(math.min(ys[1], ys[2], ys[3], ys[4]))
m[3], m[6] = tr(-(nw - w) / 2, -(nh - h) / 2)
end
local lok, le = limit(nw, nh, opts)
if not lok then
return nil, le
end
return viaRgba(img, function(im: Image): (Image?, Err.Err?)
local out = like(im, nw, nh)
local kind = K.KIND[im.format]
local alpha = ALPHA_CH[im.format]
local src = im.pixels
if alpha then
src = buffer.create(buffer.len(im.pixels))
buffer.copy(src, 0, im.pixels)
K.premultiply(src, w * h, alpha, kind, false)
end
K.affine(src, w, h, K.CHANNELS[im.format], kind, out.pixels, nw, nh, m)
if alpha then
K.premultiply(out.pixels, nw * nh, alpha, kind, true)
end
return out, nil
end)
end
local RGBA: { [string]: boolean } = { rgba8 = true, rgba16 = true, rgbaf32 = true }
export type BlitOptions = { blend: ("over" | "source")?, opacity: number? }
function ImageOps.blit(dst: Image, src: Image, x: number, y: number, opts: BlitOptions?): (Image?, Err.Err?)
local ok, e = check(dst)
if not ok then
return nil, e
end
local ok2, e2 = check(src)
if not ok2 then
return nil, e2
end
if not isInt(x) or not isInt(y) then
return arg("blit: integer x, y")
end
local blend = (opts and opts.blend) or "over"
if blend ~= "over" and blend ~= "source" then
return arg("blit: blend must be \"over\" or \"source\"")
end
local opacity = (opts and opts.opacity) or 1
if type(opacity) ~= "number" or not (opacity >= 0 and opacity <= 1) then
return arg("blit: opacity must be 0..1")
end
local sx, sy = math.max(0, -x), math.max(0, -y)
local dx, dy = math.max(0, x), math.max(0, y)
local w = math.min(src.width - sx, dst.width - dx)
local h = math.min(src.height - sy, dst.height - dy)
if w <= 0 or h <= 0 then
return dst, nil
end
if dst.format == "yuv420p" or (blend == "over" and not RGBA[dst.format]) then
-- work on an rgba copy of the region, then write it back in dst's format
local region = ImageOps.crop(dst, dx, dy, w, h) :: Image
local work = if region.format == "rgba8" then region else ImageOps.convert(region, "rgba8") :: Image
ImageOps.blit(work, src, x - dx, y - dy, opts)
if dst.format == "yuv420p" then
local full = ImageOps.convert(dst, "rgba8") :: Image
ImageOps.blit(full, work, dx, dy, { blend = "source" })
local back = ImageOps.convert(full, "yuv420p") :: Image
buffer.copy(dst.pixels, 0, back.pixels, 0, buffer.len(back.pixels))
else
local back = ImageOps.convert(work, dst.format) :: Image
K.copyRect(dst.pixels, dst.width, back.pixels, back.width, 0, 0, dx, dy, w, h, Types.BPP[dst.format] :: number)
end
return dst, nil
end
local s = src
if src.format ~= dst.format then
s = ImageOps.convert(src, dst.format) :: Image
end
if blend == "source" then
K.copyRect(dst.pixels, dst.width, s.pixels, s.width, sx, sy, dx, dy, w, h, Types.BPP[dst.format] :: number)
elseif dst.format == "rgba8" then
K.overRgba8(dst.pixels, dst.width, s.pixels, s.width, sx, sy, dx, dy, w, h, math.floor(opacity * 255 + 0.5))
else
K.overFloat(dst.pixels, dst.width, s.pixels, s.width, sx, sy, dx, dy, w, h, opacity, K.KIND[dst.format])
end
return dst, nil
end
function ImageOps.composite(dst: Image, src: Image, x: number?, y: number?, opts: BlitOptions?): (Image?, Err.Err?)
local out, e = ImageOps.copy(dst)
if not out then
return nil, e
end
out.frames = nil
return ImageOps.blit(out, src, x or 0, y or 0, opts)
end
local function premul(img: Image, un: boolean): (Image?, Err.Err?)
local out, e = ImageOps.copy(img)
if not out then
return nil, e
end
out.frames = nil
local ch = ALPHA_CH[img.format]
if ch then
K.premultiply(out.pixels, img.width * img.height, ch, K.KIND[img.format], un)
end
return out, nil
end
function ImageOps.premultiply(img: Image): (Image?, Err.Err?)
return premul(img, false)
end
function ImageOps.unpremultiply(img: Image): (Image?, Err.Err?)
return premul(img, true)
end
local MAXV: { [string]: number } = { rgba8 = 255, rgba16 = 65535, rgbaf32 = 1, rgb8 = 255, gray8 = 255, gray16 = 65535, graya8 = 255, alpha8 = 255, yuv420p = 255 }
function ImageOps.getPixel(img: Image, x: number, y: number): (any, any, number?, number?)
local ok, e = check(img)
if not ok then
return nil, e
end
if not isInt(x) or not isInt(y) or x < 0 or y < 0 or x >= img.width or y >= img.height then
return arg("getPixel: coordinates out of range")
end
local b, f, i = img.pixels, img.format, y * img.width + x
local ru8, ru16, rf = buffer.readu8, buffer.readu16, buffer.readf32
if f == "rgba8" then
return ru8(b, i * 4), ru8(b, i * 4 + 1), ru8(b, i * 4 + 2), ru8(b, i * 4 + 3)
elseif f == "rgba16" then
return ru16(b, i * 8), ru16(b, i * 8 + 2), ru16(b, i * 8 + 4), ru16(b, i * 8 + 6)
elseif f == "rgbaf32" then
return rf(b, i * 16), rf(b, i * 16 + 4), rf(b, i * 16 + 8), rf(b, i * 16 + 12)
elseif f == "rgb8" then
return ru8(b, i * 3), ru8(b, i * 3 + 1), ru8(b, i * 3 + 2), 255
elseif f == "gray8" then
local v = ru8(b, i)
return v, v, v, 255
elseif f == "gray16" then
local v = ru16(b, i * 2)
return v, v, v, 65535
elseif f == "graya8" then
local v = ru8(b, i * 2)
return v, v, v, ru8(b, i * 2 + 1)
elseif f == "alpha8" then
return 255, 255, 255, ru8(b, i)
end
local one = ImageOps.crop(img, x - x % 2, y - y % 2, 2, 2) :: Image
local rgba = ImageOps.convert(one, "rgba8") :: Image
local j = ((y % 2) * rgba.width + (x % 2)) * 4
if j + 4 > buffer.len(rgba.pixels) then
j = 0
end
return ru8(rgba.pixels, j), ru8(rgba.pixels, j + 1), ru8(rgba.pixels, j + 2), 255
end
function ImageOps.setPixel(img: Image, x: number, y: number, r: number, g: number, b: number, a: number?): (boolean?, Err.Err?)
local ok, e = check(img)
if not ok then
return nil, e
end
if not isInt(x) or not isInt(y) or x < 0 or y < 0 or x >= img.width or y >= img.height then
return arg("setPixel: coordinates out of range")
end
if type(r) ~= "number" or type(g) ~= "number" or type(b) ~= "number" or (a ~= nil and type(a) ~= "number") then
return arg("setPixel: numeric channels")
end
local f = img.format
if f == "yuv420p" then
return arg("setPixel: not supported on yuv420p (convert to rgba8 first)")
end
local max = MAXV[f]
local al = if a == nil then max else a
local function q(v: number): number
if max == 1 then
return v
end
if v ~= v then
return 0
end
return math.clamp(math.floor(v + 0.5), 0, max)
end
local px, i = img.pixels, y * img.width + x
local wu8, wu16, wf = buffer.writeu8, buffer.writeu16, buffer.writef32
local function grey(): number
if max == 1 then
return (r * 19595 + g * 38470 + b * 7471) / 65536
end
return (q(r) * 19595 + q(g) * 38470 + q(b) * 7471 + 32768) // 65536
end
if f == "rgba8" then
wu8(px, i * 4, q(r))
wu8(px, i * 4 + 1, q(g))
wu8(px, i * 4 + 2, q(b))
wu8(px, i * 4 + 3, q(al))
elseif f == "rgba16" then
wu16(px, i * 8, q(r))
wu16(px, i * 8 + 2, q(g))
wu16(px, i * 8 + 4, q(b))
wu16(px, i * 8 + 6, q(al))
elseif f == "rgbaf32" then
wf(px, i * 16, r)
wf(px, i * 16 + 4, g)
wf(px, i * 16 + 8, b)
wf(px, i * 16 + 12, al)
elseif f == "rgb8" then
wu8(px, i * 3, q(r))
wu8(px, i * 3 + 1, q(g))
wu8(px, i * 3 + 2, q(b))
elseif f == "gray8" then
wu8(px, i, grey())
elseif f == "gray16" then
wu16(px, i * 2, grey())
elseif f == "graya8" then
wu8(px, i * 2, grey())
wu8(px, i * 2 + 1, q(al))
else
wu8(px, i, q(al))
end
return true, nil
end
function ImageOps.fill(img: Image, r: number, g: number, b: number, a: number?): (Image?, Err.Err?)
local ok, e = check(img)
if not ok then
return nil, e
end
if img.format == "yuv420p" then
return arg("fill: not supported on yuv420p")
end
local sok, se = ImageOps.setPixel(img, 0, 0, r, g, b, a)
if not sok then
return nil, se
end
local bpp = Types.BPP[img.format] :: number
local n = img.width * img.height * bpp
local filled = bpp
while filled < n do
local c = math.min(filled, n - filled)
buffer.copy(img.pixels, filled, img.pixels, 0, c)
filled += c
end
return img, nil
end
function ImageOps.frameCount(img: Image): number
if type(img) == "table" and type(img.frames) == "table" and #img.frames > 0 then
return #img.frames
end
return 1
end
function ImageOps.durations(img: Image): { number }
local out = {}
if type(img) == "table" and type(img.frames) == "table" and #img.frames > 0 then
for i, f in img.frames do
out[i] = if type(f.delay) == "number" then f.delay else 0
end
return out
end
return { 0 }
end
-- coalesce: dispose "none" keeps the canvas, "background" clears the frame's rectangle, "previous" restores it
function ImageOps.coalesce(img: Image): ({ Image }?, Err.Err?)
local ok, e = check(img)
if not ok then
return nil, e
end
local frames = img.frames
if type(frames) ~= "table" or #frames == 0 then
return { img }, nil
end
local fmt = if RGBA[img.format] then img.format else "rgba8"
local canvas = Types.Image.new(img.width, img.height, fmt :: any)
local bpp = Types.BPP[fmt] :: number
local out = {}
for i, f in frames do
if type(f) ~= "table" then
return arg("coalesce: frame " .. i .. " is not a Frame")
end
local fi = f.image
local fok, fe = check(fi)
if not fok then
return nil, Err.new(Err.ARG, "coalesce: frame " .. i .. ": " .. (fe :: Err.Err).message)
end
local fx, fy = if isInt(f.x) then f.x else 0, if isInt(f.y) then f.y else 0
local saved: buffer? = nil
if f.dispose == "previous" then
local sb = buffer.create(buffer.len(canvas.pixels))
buffer.copy(sb, 0, canvas.pixels)
saved = sb
end
local bok, be = ImageOps.blit(canvas, fi, fx, fy, { blend = if f.blend == "source" then "source" else "over" })
if not bok then
return nil, be
end
local snap = Types.Image.new(img.width, img.height, fmt :: any)
buffer.copy(snap.pixels, 0, canvas.pixels)
for k, v in img.meta do
snap.meta[k] = v
end
snap.meta.delay = f.delay
out[i] = snap
if f.dispose == "background" then
local x0, y0 = math.max(0, fx), math.max(0, fy)
local x1, y1 = math.min(img.width, fx + fi.width), math.min(img.height, fy + fi.height)
for y = y0, y1 - 1 do
if x1 > x0 then
buffer.fill(canvas.pixels, (y * img.width + x0) * bpp, 0, (x1 - x0) * bpp)
end
end
elseif saved then
canvas.pixels = saved
end
end
return out, nil
end
function ImageOps.fromFrames(images: { Image }, delays: (number | { number })?): (Image?, Err.Err?)
if type(images) ~= "table" or #images == 0 then
return arg("fromFrames: a non-empty list of Images")
end
local first = images[1]
local ok, e = check(first)
if not ok then
return nil, e
end
local frames = {}
for i, im in images do
local iok, ie = check(im)
if not iok then
return nil, ie
end
if im.width ~= first.width or im.height ~= first.height or im.format ~= first.format then
return arg("fromFrames: frame " .. i .. " differs in size or format from frame 1")
end
local d = 0.1
if type(delays) == "number" then
d = delays
elseif type(delays) == "table" and type(delays[i]) == "number" then
d = delays[i]
end
frames[i] = { image = im, delay = d, x = 0, y = 0, dispose = "none", blend = "source" }
end
local out = like(first, first.width, first.height)
buffer.copy(out.pixels, 0, first.pixels, 0, buffer.len(out.pixels))
out.frames = frames :: any
out.loops = 0
return out, nil
end
return ImageOps