From 80d12dbedb67191a5eb3e4f3c36b04baed1f8afb Mon Sep 17 00:00:00 2001 From: hecks <42101236+hecktest@users.noreply.github.com> Date: Thu, 29 Jul 2021 05:10:10 +0200 Subject: Add a simple PNG image encoder with Lua API (#11485) * Add a simple PNG image encoder with Lua API Add ColorSpec to RGBA converter Make a safety wrapper for the encoder Create devtest examples Co-authored-by: hecktest <> Co-authored-by: sfan5 --- builtin/game/misc.lua | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) (limited to 'builtin') diff --git a/builtin/game/misc.lua b/builtin/game/misc.lua index c13a583f0..cee95dd23 100644 --- a/builtin/game/misc.lua +++ b/builtin/game/misc.lua @@ -290,3 +290,42 @@ function core.dynamic_add_media(filepath, callback) end return true end + + +-- PNG encoder safety wrapper + +local o_encode_png = core.encode_png +function core.encode_png(width, height, data, compression) + if type(width) ~= "number" then + error("Incorrect type for 'width', expected number, got " .. type(width)) + end + if type(height) ~= "number" then + error("Incorrect type for 'height', expected number, got " .. type(height)) + end + + local expected_byte_count = width * height * 4; + + if type(data) ~= "table" and type(data) ~= "string" then + error("Incorrect type for 'height', expected table or string, got " .. type(height)); + end + + local data_length = type(data) == "table" and #data * 4 or string.len(data); + + if data_length ~= expected_byte_count then + error(string.format( + "Incorrect length of 'data', width and height imply %d bytes but %d were provided", + expected_byte_count, + data_length + )) + end + + if type(data) == "table" then + local dataBuf = {} + for i = 1, #data do + dataBuf[i] = core.colorspec_to_bytes(data[i]) + end + data = table.concat(dataBuf) + end + + return o_encode_png(width, height, data, compression or 6) +end -- cgit v1.2.3