From 9bd1702d60c63636db4ec93611b623dbb6648171 Mon Sep 17 00:00:00 2001 From: Nils Dagsson Moskopp Date: Sun, 15 May 2022 14:54:28 +0200 Subject: [PATCH] Encode image only when saving it to a file --- examples.lua | 9 +++++---- init.lua | 18 +++++++++--------- 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/examples.lua b/examples.lua index 0b5b55609..4d04e6e8a 100644 --- a/examples.lua +++ b/examples.lua @@ -39,7 +39,7 @@ for x = 1,6,1 do -- left to right pixels[z][x] = color end end -tga_encoder.image(pixels, {colors="BW", pixel_depth=8}):save("gradients_8bpp.tga") +tga_encoder.image(pixels):save("gradients_8bpp.tga", {colors="BW", pixel_depth=8}) local pixels = {} for x = 1,16,1 do -- left to right @@ -58,8 +58,9 @@ for x = 1,16,1 do -- left to right pixels[z][x] = color end end -tga_encoder.image(pixels, {colors="RGB", pixel_depth=16}):save("gradients_16bpp.tga") -tga_encoder.image(pixels, {colors="RGB", pixel_depth=24}):save("gradients_24bpp.tga") +local gradients = tga_encoder.image(pixels) +gradients:save("gradients_16bpp.tga", {colors="RGB", pixel_depth=16}) +gradients:save("gradients_24bpp.tga", {colors="RGB", pixel_depth=24}) local pixels = {} for x = 1,512,1 do -- left to right @@ -81,4 +82,4 @@ for x = 1,512,1 do -- left to right pixels[z][x] = color end end -tga_encoder.image(pixels, {colors="RGB", pixel_depth=24}):save("fractal_24bpp.tga") +tga_encoder.image(pixels):save("fractal_24bpp.tga", {colors="RGB", pixel_depth=24}) diff --git a/init.lua b/init.lua index aad7f2cac..a79a32920 100644 --- a/init.lua +++ b/init.lua @@ -8,17 +8,10 @@ local image = setmetatable({}, { end, }) -function image:constructor(pixels, properties) - local properties = properties or {} - properties.colors = properties.colors or "RGB" - properties.pixel_depth = properties.pixel_depth or 16 - - self.data = "" +function image:constructor(pixels) self.pixels = pixels self.width = #pixels[1] self.height = #pixels - - self:encode(properties) end function image:encode_colormap_spec() @@ -263,6 +256,7 @@ function image:encode_footer() end function image:encode(properties) + self.data = "" self:encode_header(properties) -- header -- no color map and image id data self:encode_data(properties) -- encode data @@ -270,7 +264,13 @@ function image:encode(properties) self:encode_footer() -- footer end -function image:save(filename) +function image:save(filename, properties) + local properties = properties or {} + properties.colors = properties.colors or "RGB" + properties.pixel_depth = properties.pixel_depth or 16 + + self:encode(properties) + local f = assert(io.open(filename, "wb")) f:write(self.data) f:close()