diff options
Diffstat (limited to 'builtin')
-rw-r--r-- | builtin/game/misc.lua | 39 |
1 files changed, 39 insertions, 0 deletions
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 |