]> git.lizzy.rs Git - dragonfireclient.git/blobdiff - builtin/game/misc.lua
Add a simple PNG image encoder with Lua API (#11485)
[dragonfireclient.git] / builtin / game / misc.lua
index c13a583f0b7a9fcb40d45622a462e40361b8e789..cee95dd23c0390710079d7cb9cc37e67b74da001 100644 (file)
@@ -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